﻿using Microsoft.Extensions.Logging;
using RotovapPlatform.Domain.Business.Machine.Enums;
using RotovapPlatform.Domain.Business.Recipes.Entities;
using RotovapPlatform.Domain.Business.Storage.Enums;
using RotovapPlatform.Domain.Common;
using RotovapPlatform.Domain.Equipment.Device.IO;
using RotovapPlatform.Domain.Equipment.Device.Motors.Dto;
using RotovapPlatform.Domain.Equipment.Device.OilBath.Dto;
using RotovapPlatform.Domain.Equipment.Device.Robot.Dto;
using RotovapPlatform.Domain.Equipment.Device.Robot.Enums;
using RotovapPlatform.Domain.Equipment.Device.TCU.Dto;
using RotovapPlatform.Domain.Equipment.Device.TemperatureCollector.Dto;
using RotovapPlatform.Domain.Equipment.Interfaces.Services;
using RotovapPlatform.Domain.Services.Data;
using RotovapPlatform.Domain.Services.Devices;
using RotovapPlatform.Domain.Services.Storages;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using static RotovapPlatform.Domain.Business.Machine.Enums.ExperimentConfigEnums;
using RotovapPlatform.Domain.Models.Temperature;
using System.Globalization;
using System;
using System.Diagnostics;

namespace RotovapPlatform.Domain.Services.Experiments
{
	/// <summary>
	/// 实验流程领域服务实现
	/// </summary>
	public class ExperimentProcessDomainService : IExperimentProcessDomainService, IDisposable
	{
		private readonly ILogger<ExperimentProcessDomainService> _logger;
		private readonly IDeviceDomainService _deviceService;
		private readonly IStorageDomainService _storageService;
		private readonly IDataRecordingDomainService _dataRecordingService;
		private readonly IDeviceManager _deviceManager;
		private readonly IDeviceStatusService _deviceStatusService;
		private readonly IMotorControlService _motorControlService;

		private Guid? _currentExperimentId;
		private ExperimentStage? _currentStage;
		private ExperimentSubStage? _currentSubStage;



		//离心瓶体积
		private static double _centrifugeBottleVolume = 500;
		//1000ml旋蒸瓶打液量
		private static double _rotaryPumpVolume1000ml = 450;
		//500ml旋蒸瓶打液量
		private static double _rotaryPumpVolume500ml = 350;


		//旋蒸空瓶位置
		private static int _rotaryEmptyBottlePosition;
		//原料离心瓶位置
		private static int _materialCentrifugePosition;
		//冷凝液收集瓶位置
		private static int _condenserLiquidCollectionPosition;
		//取样瓶空瓶位置
		private static int _sampleEmptyBottlePosition;
		//是否抽液平台抽液位占位		
		private static bool _isExtractLiquidOccupy;
		//是否抽液平台收集位占位
		private static bool _isCollectLiquidOccupy;

		//是否物料瓶多瓶
		private static bool _isMultiVial;
		//当前物料瓶索引
		private static int _currentVialIndex;
		//物料瓶数量
		private static int _materialVialCount;
		//是否是最后一瓶物料瓶
		private static bool _isLastMaterialVial;
		//实验原料瓶位置数组
		private static ObservableCollection<int> _materialVialPositions;
		//旋蒸瓶类型
		private static ItemType _rotaryBottleType;
		//打液量
		private static double _rotaryPumpVolume;
		//当前旋蒸原液是否打完	
		private static bool _isCurrentMaterialLiquidFinished;


		//产物数量
		private static int _productCount;
		//当前产物参数
		private static int _currentProductIndex;
		//油浴温度
		private static double _oilBathTemperature;
		//冷凝器温度
		private static double _condenserTemperature;
		//旋蒸转速
		private static double _rotarySpeed;
		//冷凝器压力设定
		private static double _condenserPressureSet;
		//冷凝液是否收集
		private static bool _isCondensateLiquidCollected;
		//冷凝液是否取样
		private static bool _isCondensateLiquidSampled;
		//旋蒸时间min
		private static double _evaporationTime;
		//是否智能控温
		private static bool _isSmartTemperatureControl;

		//旋蒸残液是否取样
		private static bool _isEvaporationResidueSampled;
		//旋蒸残液是否收集
		private static bool _isEvaporationResidueCollected;



		//旋蒸瓶旋紧后角度
		private static double _rotaryBottleTightenAngle;
		//补液情况 0-无须补液 1-未打完补液 2-打完换瓶补液
		private static int _refillSituation;
		//未打完液体量
		private static double _unPumpedLiquidVolume;


		// 设备状态缓存属性
		private Dictionary<string, MotorStatus> _motorStatusCache = new();
		private Dictionary<string, TCUStatus> _tcuStatusCache = new();
		private Dictionary<string, OilBathStatus> _oilBathStatusCache = new();
		private Dictionary<string, TemperatureCollectorStatus> _tempCollectorStatusCache = new();
		private Dictionary<DISignalId, bool> _diSignalStatusCache = new();
		private Dictionary<DOSignalId, bool> _doSignalStatusCache = new();
		private RobotStatusDto _robotStatus = new();
		private RobotTaskFeedBackDto _robotTaskStatus = new();
		private double _condenserPressure = 0;

		// 常用设备状态属性 - 提供便捷访问
		public MotorStatus RotaryMotorStatus => GetMotorStatus("RotovapRotaryMotor");
		public MotorStatus LiftMotorStatus => GetMotorStatus("RotovapLiftMotor");
		public MotorStatus OilBathMotorStatus => GetMotorStatus("OilBathMotor");
		public TCUStatus MainTCUStatus => GetTCUStatus("TCU_502_1");
		public OilBathStatus MainOilBathStatus => GetOilBathStatus("c");
		public TemperatureCollectorStatus MainTempCollectorStatus => GetTempCollectorStatus("TempCollector_504_1");
		public bool IsRobotReady => _robotStatus.IsPoweredOn &&
								   _robotStatus.IsEnabled &&
								   !_robotStatus.IsMoving &&
								   _robotTaskStatus.RobotProcessState == RobotProcessState.Idle;
		public bool IsRobotArrival1 => _robotStatus.IsPoweredOn &&
								   _robotStatus.IsEnabled &&
								   !_robotStatus.IsMoving &&
								   _robotTaskStatus.RobotProcessState == RobotProcessState.InTask &&
								   _robotTaskStatus.RobotArrivedSignal_1 != 0;

		public int RobotArrival_Value1 => _robotTaskStatus.RobotArrivedSignal_1;


		public double CondenserPressure => _condenserPressure;

		public event EventHandler<ExperimentStageChangedEventArgs> ExperimentStageChanged;
		public event EventHandler<ExperimentSubStageChangedEventArgs> ExperimentSubStageChanged;

		public Guid? CurrentExperimentId => _currentExperimentId;
		public ExperimentStage? CurrentStage => _currentStage;
		public ExperimentSubStage? CurrentSubStage => _currentSubStage;

		// 用于信号等待取消的字典，键为信号ID，值为是否取消
		private Dictionary<DISignalId, bool> _signalWaitCancelFlags = new Dictionary<DISignalId, bool>();
		private volatile bool _cancelSignalWait = false; // 保留全局取消标志用于向后兼容

		// 用于自动调压的取消标记
		private CancellationTokenSource _pressureControlCts;

		private volatile bool _cancelLiquidMonitoring = false; // 用于取消液位监测的标记

		private TemperatureJudgmentData _temperatureJudgmentData = new TemperatureJudgmentData();

		/// <summary>
		/// 智能温度判别数据，用于监测和分析温度变化
		/// </summary>
		public TemperatureJudgmentData TemperatureJudgmentData => _temperatureJudgmentData;

		/// <summary>
		/// 构造函数
		/// </summary>
		public ExperimentProcessDomainService(
			ILogger<ExperimentProcessDomainService> logger,
			IDeviceDomainService deviceService,
			IStorageDomainService storageService,
			IDataRecordingDomainService dataRecordingService,
			IDeviceManager deviceManager,
			IDeviceStatusService deviceStatusService,
			IMotorControlService motorControlService)
		{
			_logger = logger;
			_deviceService = deviceService;
			_storageService = storageService;
			_dataRecordingService = dataRecordingService;
			_deviceManager = deviceManager;
			_deviceStatusService = deviceStatusService;
			_motorControlService = motorControlService;

			// 注册设备状态变化事件
			_deviceStatusService.DeviceStatusChanged += OnDeviceStatusChanged;

			// 初始化DI/DO信号缓存
			InitializeSignalCache();
		}

		/// <summary>
		/// 初始化DI/DO信号缓存
		/// </summary>
		private void InitializeSignalCache()
		{
			// 初始化DI信号缓存
			foreach (DISignalId id in Enum.GetValues(typeof(DISignalId)))
			{
				_diSignalStatusCache[id] = false;
			}

			// 初始化DO信号缓存
			foreach (DOSignalId id in Enum.GetValues(typeof(DOSignalId)))
			{
				_doSignalStatusCache[id] = false;
			}
		}

		/// <summary>
		/// 设备状态变化事件处理
		/// </summary>
		private void OnDeviceStatusChanged(object sender, DeviceStatusEventArgs e)
		{
			try
			{
				// 处理各种设备状态变化
				if (e.DeviceId.StartsWith("Motor_"))
				{
					// 更新电机状态缓存
					if (e.Status is MotorStatus motorStatus)
					{
						string motorId = e.DeviceId;
						_motorStatusCache[motorId] = motorStatus;
					}
				}
				else if (e.DeviceId.StartsWith("TCU_"))
				{
					// 更新TCU状态缓存
					if (e.Status is TCUStatus tcuStatus)
					{
						string tcuId = e.DeviceId;
						_tcuStatusCache[tcuId] = tcuStatus;
					}
				}
				else if (e.DeviceId.StartsWith("OilBath_"))
				{
					// 更新油浴锅状态缓存
					if (e.Status is OilBathStatus oilBathStatus)
					{
						string oilBathId = e.DeviceId;
						_oilBathStatusCache[oilBathId] = oilBathStatus;
					}
				}
				else if (e.DeviceId.StartsWith("TempCollector_"))
				{
					// 更新温度采集模块状态缓存
					if (e.Status is TemperatureCollectorStatus tempCollectorStatus)
					{
						string collectorId = e.DeviceId;
						_tempCollectorStatusCache[collectorId] = tempCollectorStatus;
					}
				}
				else if (e.DeviceId == "RobotDevice")
				{
					// 更新机器人设备状态
					if (e.Status is RobotStatusDto robotStatus)
					{
						_robotStatus = robotStatus;
					}
				}
				else if (e.DeviceId == "RobotTask")
				{
					// 更新机器人任务状态
					if (e.Status is RobotTaskFeedBackDto taskStatus)
					{
						_robotTaskStatus = taskStatus;
					}
				}
				else if (e.DeviceId == "CondenserPressure")
				{
					// 更新冷凝器压力值
					if (e.Status is double pressure)
					{
						_condenserPressure = pressure;
					}
				}
				else if (e.DeviceId.StartsWith("DI") && IOSignalUtils.TryParseDISignalId(e.DeviceId, out DISignalId diId))
				{
					// 更新DI信号状态
					if (e.Status is bool diState)
					{
						_diSignalStatusCache[diId] = diState;
					}
				}
				else if (e.DeviceId.StartsWith("DO") && IOSignalUtils.TryParseDOSignalId(e.DeviceId, out DOSignalId doId))
				{
					// 更新DO信号状态
					if (e.Status is bool doState)
					{
						_doSignalStatusCache[doId] = doState;
					}
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"处理设备状态变化事件异常: {e.DeviceId}");
			}
		}

		/// <summary>
		/// 获取电机状态 - 优先从缓存获取，如果缓存中不存在则从服务获取
		/// </summary>
		private MotorStatus GetMotorStatus(string motorId)
		{
			if (_motorStatusCache.TryGetValue(motorId, out var status))
			{
				return status;
			}

			// 缓存中不存在，从服务获取
			try
			{
				var statusTask = _deviceStatusService.GetMotorStatusAsync(motorId);
				statusTask.Wait();
				var fetchedStatus = statusTask.Result;
				_motorStatusCache[motorId] = fetchedStatus;
				return fetchedStatus;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"获取电机 {motorId} 状态失败");
				return new MotorStatus { Offline = true };
			}
		}

		/// <summary>
		/// 获取TCU状态
		/// </summary>
		private TCUStatus GetTCUStatus(string tcuId)
		{
			if (_tcuStatusCache.TryGetValue(tcuId, out var status))
			{
				return status;
			}

			// 缓存中不存在，从服务获取
			try
			{
				var statusTask = _deviceStatusService.GetTCUStatusAsync(tcuId);
				statusTask.Wait();
				var fetchedStatus = statusTask.Result;
				_tcuStatusCache[tcuId] = fetchedStatus;
				return fetchedStatus;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"获取TCU {tcuId} 状态失败");
				return new TCUStatus();
			}
		}

		/// <summary>
		/// 获取油浴锅状态
		/// </summary>
		private OilBathStatus GetOilBathStatus(string oilBathId)
		{
			if (_oilBathStatusCache.TryGetValue(oilBathId, out var status))
			{
				return status;
			}

			// 缓存中不存在，从服务获取
			try
			{
				var statusTask = _deviceStatusService.GetOilBathStatusAsync(oilBathId);
				statusTask.Wait();
				var fetchedStatus = statusTask.Result;
				_oilBathStatusCache[oilBathId] = fetchedStatus;
				return fetchedStatus;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"获取油浴锅 {oilBathId} 状态失败");
				return new OilBathStatus();
			}
		}

		/// <summary>
		/// 获取温度采集模块状态
		/// </summary>
		private TemperatureCollectorStatus GetTempCollectorStatus(string collectorId)
		{
			if (_tempCollectorStatusCache.TryGetValue(collectorId, out var status))
			{
				return status;
			}

			// 缓存中不存在，从服务获取
			try
			{
				var statusTask = _deviceStatusService.GetTemperatureCollectorStatusAsync(collectorId);
				statusTask.Wait();
				var fetchedStatus = statusTask.Result;
				_tempCollectorStatusCache[collectorId] = fetchedStatus;
				return fetchedStatus;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"获取温度采集模块 {collectorId} 状态失败");
				return new TemperatureCollectorStatus();
			}
		}

		/// <summary>
		/// 获取DI信号状态 - 从缓存获取
		/// </summary>
		public bool GetDISignalState(DISignalId id)
		{
			if (_diSignalStatusCache.TryGetValue(id, out var state))
			{
				return state;
			}

			// 缓存中不存在，从服务获取
			var signal = _deviceStatusService.GetDISignal(id);
			bool signalState = signal?.State ?? false;
			_diSignalStatusCache[id] = signalState;
			return signalState;
		}

		/// <summary>
		/// 获取DO信号状态 - 从缓存获取
		/// </summary>
		public bool GetDOSignalState(DOSignalId id)
		{
			if (_doSignalStatusCache.TryGetValue(id, out var state))
			{
				return state;
			}

			// 缓存中不存在，从服务获取
			var signal = _deviceStatusService.GetDOSignal(id);
			bool signalState = signal?.State ?? false;
			_doSignalStatusCache[id] = signalState;
			return signalState;
		}

		#region 辅助方法

		/// <summary>
		/// 触发实验阶段变更事件
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <param name="stage">实验阶段</param>
		private void OnExperimentStageChanged(Guid experimentId, ExperimentStage stage)
		{
			_currentExperimentId = experimentId;
			_currentStage = stage;
			ExperimentStageChanged?.Invoke(this, new ExperimentStageChangedEventArgs(experimentId, stage));
			_logger.LogInformation($"实验 {experimentId} 阶段变更为: {stage}");
		}

		/// <summary>
		/// 触发实验子阶段变更事件
		/// </summary>
		/// <param name="experimentId">实验ID</param>
		/// <param name="stage">实验阶段</param>
		/// <param name="subStage">实验子阶段</param>
		private void OnExperimentSubStageChanged(Guid experimentId, ExperimentStage stage, ExperimentSubStage subStage)
		{
			_currentExperimentId = experimentId;
			_currentStage = stage;
			_currentSubStage = subStage;
			ExperimentSubStageChanged?.Invoke(this, new ExperimentSubStageChangedEventArgs(experimentId, stage, subStage));
			_logger.LogInformation($"实验 {experimentId} 子阶段变更为: {subStage}");
		}

		/// <summary>
		/// 更新产物当前参数
		/// </summary>
		/// <param name="experiment">实验</param>
		private void UpdateProductCurrentParameters(Experiment experiment)
		{
			_oilBathTemperature = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].OilTemperature;
			_condenserTemperature = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].CondensationTemperature;
			_rotarySpeed = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].RotarySpeed;
			_condenserPressureSet = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].Vacuum;
			_isCondensateLiquidCollected = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].IsCondensationCollect;
			_isCondensateLiquidSampled = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].IsCondensationCollect;
			_isSmartTemperatureControl = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].IsSmartTemperatureJudgment;
			_evaporationTime = experiment.ExecutionParameters.ProductParameters[_currentProductIndex].RotaryTime;
			_isEvaporationResidueSampled = experiment.ExecutionParameters.ResidualLiquidParameters.IsSampling;
			_isEvaporationResidueCollected = experiment.ExecutionParameters.ResidualLiquidParameters.IsResidualLiquidCollect;
		}

		/// <summary>
		/// 执行并记录实验子阶段
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <param name="subStage">子阶段</param>
		/// <param name="action">执行操作</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> ExecuteSubStageAsync(
			Experiment experiment,
			ExperimentSubStage subStage,
			Func<Task> action)
		{
			try
			{
				// 更新实验子阶段
				experiment.CurrentSubStage = subStage;
				_currentExperimentId = experiment.ExperimentId;

				// 触发子阶段变更事件
				OnExperimentSubStageChanged(experiment.ExperimentId, experiment.CurrentStage, subStage);

				// 记录子阶段开始
				await _dataRecordingService.RecordExperimentStageChangeAsync(
					experiment.ExperimentId,
					experiment.CurrentStage,
					subStage,
					StageChangeType.Start);

				_logger.LogInformation($"实验 {experiment.ExperimentId} 进入子阶段: {subStage}");

				// 执行子阶段操作
				await action();

				// 记录子阶段完成
				await _dataRecordingService.RecordExperimentStageChangeAsync(
					experiment.ExperimentId,
					experiment.CurrentStage,
					subStage,
					StageChangeType.Complete);

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"实验 {experiment.ExperimentId} 执行子阶段 {subStage} 时发生错误: {ex.Message}");

				// 记录子阶段失败
				await _dataRecordingService.RecordExperimentStageChangeAsync(
					experiment.ExperimentId,
					experiment.CurrentStage,
					subStage,
					StageChangeType.Fail);

				// 修改子阶段为错误状态
				experiment.CurrentSubStage = ExperimentSubStage.Error;

				// 触发错误状态变更事件
				OnExperimentSubStageChanged(experiment.ExperimentId, experiment.CurrentStage, ExperimentSubStage.Error);

				return new OperationResult { Success = false, Message = ex.Message };
			}
		}

		/// <summary>
		/// 处理实验错误
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <param name="errorMessage">错误信息</param>
		/// <param name="attemptRecovery">是否尝试恢复</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> HandleExperimentErrorAsync(
			Experiment experiment,
			string errorMessage,
			bool attemptRecovery = true)
		{
			try
			{
				_logger.LogWarning($"处理实验 {experiment.ExperimentId} 错误: {errorMessage}");

				// 记录错误
				await _dataRecordingService.RecordExperimentEventAsync(
					experiment.ExperimentId,
					"ExperimentError",
					errorMessage);

				// 如果不尝试恢复，直接将实验标记为失败
				if (!attemptRecovery)
				{
					experiment.Status = ExperimentStatus.Failed;
					experiment.CurrentStage = ExperimentStage.Failed;

					// 触发阶段变更事件
					OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.Failed);
					OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.Failed, ExperimentSubStage.Error);

					return new OperationResult { Success = false, Message = $"实验失败: {errorMessage}" };
				}

				// 根据当前阶段和子阶段尝试恢复
				bool recoverySucceeded = false;
				string recoveryMessage = "";

				//switch (experiment.CurrentStage)
				//{
				//	case ExperimentStage.MaterialAndConditionPreparation:
				//		(recoverySucceeded, recoveryMessage) = await RecoverFromMaterialAndConditionPreparationErrorAsync(experiment);
				//		break;
				//	case ExperimentStage.RotaryEvaporation:
				//		(recoverySucceeded, recoveryMessage) = await RecoverFromRotaryEvaporationErrorAsync(experiment);
				//		break;
				//	case ExperimentStage.EvaporationResidueProcessing:
				//		(recoverySucceeded, recoveryMessage) = await RecoverFromEvaporationResidueProcessingErrorAsync(experiment);
				//		break;
				//	case ExperimentStage.CondensateProcessing:
				//		(recoverySucceeded, recoveryMessage) = await RecoverFromCondensateProcessingErrorAsync(experiment);
				//		break;
				//	case ExperimentStage.Cleaning:
				//		(recoverySucceeded, recoveryMessage) = await RecoverFromCleaningErrorAsync(experiment);
				//		break;
				//	default:
				//		recoverySucceeded = false;
				//		recoveryMessage = "无法恢复未知阶段的错误";
				//		break;
				//}

				// 如果恢复成功，继续执行实验
				if (recoverySucceeded)
				{
					_logger.LogInformation($"实验 {experiment.ExperimentId} 从错误中恢复成功: {recoveryMessage}");

					await _dataRecordingService.RecordExperimentEventAsync(
						experiment.ExperimentId,
						"ExperimentRecovered",
						recoveryMessage);

					return new OperationResult { Success = true, Message = recoveryMessage };
				}
				else
				{
					// 恢复失败，将实验标记为失败
					_logger.LogWarning($"实验 {experiment.ExperimentId} 恢复失败: {recoveryMessage}");

					experiment.Status = ExperimentStatus.Failed;
					experiment.CurrentStage = ExperimentStage.Failed;

					// 触发阶段变更事件
					OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.Failed);
					OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.Failed, ExperimentSubStage.Error);

					return new OperationResult { Success = false, Message = $"实验失败: {errorMessage}；恢复尝试失败: {recoveryMessage}" };
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"处理实验 {experiment.ExperimentId} 错误时发生异常");
				return new OperationResult { Success = false, Message = $"处理错误时发生异常: {ex.Message}" };
			}
		}

		/// <summary>
		/// 等待指定的DI信号达到预期状态
		/// </summary>
		/// <param name="signalId">信号ID</param>
		/// <param name="expectedState">期望状态</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <param name="holdTimeMs">维持时间(毫秒)，信号需要保持在预期状态至少这么长时间才算成功</param>
		/// <returns>是否成功等待到信号状态变为预期值</returns>
		public async Task<OperationResult> WaitForSignalStateAsync(DISignalId signalId, bool expectedState, int timeoutMs, int holdTimeMs = 100)
		{
			var startTime = DateTime.Now;
			DateTime? stateReachedTime = null; // 记录首次达到预期状态的时间

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				// 优先使用缓存中的状态
				bool currentState = GetDISignalState(signalId);

				if (currentState == expectedState)
				{
					// 如果是首次达到预期状态，记录时间
					if (stateReachedTime == null)
					{
						stateReachedTime = DateTime.Now;
						_logger.LogDebug($"信号 {signalId} 首次达到预期状态: {expectedState}，开始计算持续时间");
					}

					// 检查是否已经维持了足够的时间
					if (holdTimeMs <= 0 || (DateTime.Now - stateReachedTime.Value).TotalMilliseconds >= holdTimeMs)
					{
						_logger.LogInformation($"信号 {signalId} 已达到预期状态: {expectedState}{(holdTimeMs > 0 ? $"，并已维持 {holdTimeMs}ms" : "")}");
						return OperationResult.Ok($"信号 {signalId} 已达到预期状态: {expectedState}{(holdTimeMs > 0 ? $"，并已维持 {holdTimeMs}ms" : "")}");
					}

					// 达到预期状态但还未维持足够时间，继续等待
					_logger.LogDebug($"信号 {signalId} 已达到预期状态: {expectedState}，但需要继续维持，已维持: {(DateTime.Now - stateReachedTime.Value).TotalMilliseconds:F0}ms / 目标: {holdTimeMs}ms");
				}
				else
				{
					// 如果信号状态变化，重置计时
					if (stateReachedTime != null)
					{
						_logger.LogDebug($"信号 {signalId} 状态变更: {expectedState} -> {currentState}，重置持续时间计时");
						stateReachedTime = null;
					}
				}

				await Task.Delay(500); // 轮询间隔100ms
			}

			// 检查超时时是否已部分达到条件
			if (stateReachedTime != null)
			{
				int actualHoldTime = (int)(DateTime.Now - stateReachedTime.Value).TotalMilliseconds;
				_logger.LogWarning($"等待信号 {signalId} 达到状态 {expectedState} 并维持 {holdTimeMs}ms 超时，实际仅维持了 {actualHoldTime}ms");
				return OperationResult.Fail($"等待信号 {signalId} 达到状态 {expectedState} 并维持 {holdTimeMs}ms 超时，实际仅维持了 {actualHoldTime}ms");
			}
			else
			{
				_logger.LogWarning($"等待信号 {signalId} 达到状态 {expectedState} 超时，信号未达到预期状态");
				return OperationResult.Fail($"等待信号 {signalId} 达到状态 {expectedState} 超时（{timeoutMs}ms），信号未达到预期状态");
			}
		}


		/// <summary>
		/// 等待机器人信号
		/// </summary>
		/// <param name="signalType">信号类型:0-Ready,1-过程交接，2-结束信号</param>
		/// <param name="signalValue">信号值</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForRobotSignalAsync(int signalType, int signalValue, int timeoutMs = 30000)
		{
			var startTime = DateTime.Now;
			_logger.LogInformation($"开始等待机器人信号，实验ID: {_currentExperimentId}");

			while (timeoutMs > 0)
			{
				switch (signalType)
				{
					case 0:
						if (IsRobotReady)
						{
							_logger.LogInformation($"机器人已就绪，实验ID: {_currentExperimentId}");
							return OperationResult.Ok("机器人已就绪");
						}
						break;
					case 1:
						if (RobotArrival_Value1 == signalValue)
						{
							_logger.LogInformation($"机器人已到达{RobotArrival_Value1}，实验ID: {_currentExperimentId}");
							return OperationResult.Ok($"机器人已到达{RobotArrival_Value1}");
						}
						break;
					case 2:
						if (_robotTaskStatus.RobotTaskFinishState == signalValue && IsRobotReady)
						{
							_logger.LogInformation($"机器人任务完成，实验ID: {_currentExperimentId}");
							return OperationResult.Ok($"机器人任务完成");
						}
						break;
					default:
						return OperationResult.Fail($"无效的机器人信号类型: {signalType}");
				}

				// 如果不是通过缓存检查，则可以通过服务获取最新状态
				if (!_robotStatus.IsPoweredOn || !_robotStatus.IsEnabled)
				{
					// 可能需要手动上电和使能
					_logger.LogWarning($"机器人未上电或未使能, 状态: 电源={_robotStatus.IsPoweredOn}, 使能={_robotStatus.IsEnabled}");
				}
				timeoutMs -= 1000;
				await Task.Delay(1000); // 检查间隔
			}

			_logger.LogError($"等待机器人就绪超时，实验ID: {_currentExperimentId}");
			return OperationResult.Fail($"等待机器人就绪超时（{timeoutMs}ms）");
		}



		/// <summary>
		/// 等待多个信号组合状态
		/// </summary>
		/// <param name="signalStates">期望的信号状态字典</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForSignalCombinationAsync(Dictionary<DISignalId, bool> signalStates, int timeoutMs = 10000)
		{
			if (signalStates == null || !signalStates.Any())
			{
				return OperationResult.Fail("信号组合为空");
			}

			var startTime = DateTime.Now;
			var signalIds = string.Join(", ", signalStates.Keys);
			_logger.LogInformation($"开始等待信号组合: {signalIds}");

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				bool allMatch = true;

				foreach (var signalState in signalStates)
				{
					bool currentState = GetDISignalState(signalState.Key);
					if (currentState != signalState.Value)
					{
						allMatch = false;
						break;
					}
				}

				if (allMatch)
				{
					_logger.LogInformation($"所有信号已达到期望状态: {signalIds}");
					return OperationResult.Ok("所有信号已达到期望状态");
				}

				await Task.Delay(500); // 轮询间隔
			}

			_logger.LogWarning($"等待信号组合超时: {signalIds}");
			return OperationResult.Fail($"等待信号组合超时（{timeoutMs}ms）: {signalIds}");
		}

		/// <summary>
		/// 等待油浴锅温度达到目标温度
		/// </summary>
		/// <param name="oilBathId">油浴锅ID</param>
		/// <param name="targetTemp">目标温度</param>
		/// <param name="tolerance">允许误差</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForOilBathTemperatureAsync(string oilBathId, double targetTemp, double tolerance = 1.0, int timeoutMs = 300000)
		{
			var startTime = DateTime.Now;
			_logger.LogInformation($"开始等待油浴锅 {oilBathId} 温度达到 {targetTemp}°C (误差±{tolerance}°C)");

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				var status = GetOilBathStatus(oilBathId);

				// 检查当前温度是否在目标温度范围内
				if (Math.Abs(status.CurrentTemperaturePV - targetTemp) <= tolerance)
				{
					_logger.LogInformation($"油浴锅 {oilBathId} 温度已达到目标: 当前={status.CurrentTemperaturePV}°C, 目标={targetTemp}°C");
					return OperationResult.Ok($"油浴锅温度已达到目标: {status.CurrentTemperaturePV}°C");
				}

				_logger.LogDebug($"油浴锅 {oilBathId} 当前温度: {status.CurrentTemperaturePV}°C, 目标: {targetTemp}°C");
				await Task.Delay(1000); // 检查间隔
			}

			_logger.LogWarning($"等待油浴锅 {oilBathId} 温度达到 {targetTemp}°C 超时");
			return OperationResult.Fail($"等待油浴锅温度达到目标值超时（{timeoutMs}ms）");
		}

		/// <summary>
		/// 等待冷凝器压力达到目标值
		/// </summary>
		/// <param name="targetPressure">目标压力</param>
		/// <param name="tolerance">允许误差</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForCondenserPressureAsync(double targetPressure, double tolerance = 5.0, int timeoutMs = 120000)
		{
			var startTime = DateTime.Now;
			_logger.LogInformation($"开始等待冷凝器压力达到 {targetPressure} (误差±{tolerance})");

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				// 获取最新压力值，因为这个值可能不是通过事件更新的
				_condenserPressure = _deviceStatusService.GetCondenserPressure();

				// 检查当前压力是否在目标范围内
				if (Math.Abs(_condenserPressure - targetPressure) <= tolerance)
				{
					_logger.LogInformation($"冷凝器压力已达到目标: 当前={_condenserPressure}, 目标={targetPressure}");
					return OperationResult.Ok($"冷凝器压力已达到目标: {_condenserPressure}");
				}

				_logger.LogDebug($"冷凝器当前压力: {_condenserPressure}, 目标: {targetPressure}");
				await Task.Delay(1000); // 检查间隔
			}

			_logger.LogWarning($"等待冷凝器压力达到 {targetPressure} 超时");
			return OperationResult.Fail($"等待冷凝器压力达到目标值超时（{timeoutMs}ms）");
		}

		/// <summary>
		/// 等待TCU温度达到目标值
		/// </summary>
		/// <param name="tcuId">TCU ID</param>
		/// <param name="targetTemp">目标温度</param>
		/// <param name="tolerance">允许误差</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForTCUTemperatureAsync(string tcuId, double targetTemp, double tolerance = 1.0, int timeoutMs = 300000)
		{
			var startTime = DateTime.Now;
			_logger.LogInformation($"开始等待TCU {tcuId} 温度达到 {targetTemp}°C (误差±{tolerance}°C)");

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				var status = GetTCUStatus(tcuId);

				// 检查当前温度是否在目标温度范围内
				if (Math.Abs(status.MainTemperature - targetTemp) <= tolerance)
				{
					_logger.LogInformation($"TCU {tcuId} 温度已达到目标: 当前={status.MainTemperature}°C, 目标={targetTemp}°C");
					return OperationResult.Ok($"TCU温度已达到目标: {status.MainTemperature}°C");
				}

				_logger.LogDebug($"TCU {tcuId} 当前温度: {status.MainTemperature}°C, 目标: {targetTemp}°C");
				await Task.Delay(1000); // 检查间隔
			}

			_logger.LogWarning($"等待TCU {tcuId} 温度达到 {targetTemp}°C 超时");
			return OperationResult.Fail($"等待TCU温度达到目标值超时（{timeoutMs}ms）");
		}

		/// <summary>
		/// 等待TCU启动信号
		/// </summary>
		/// <param name="tcuId">TCU ID</param>
		/// <param name="targetState">目标状态</param>
		/// <param name="timeoutMs">超时时间(毫秒)</param>
		/// <returns>等待结果</returns>
		public async Task<OperationResult> WaitForTCUStartSignalAsync(string tcuId, bool targetState, int timeoutMs = 30000)
		{
			var startTime = DateTime.Now;
			_logger.LogInformation($"开始等待TCU {tcuId} 启动信号达到 {targetState}");

			while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
			{
				var status = GetTCUStatus(tcuId);

				// 检查当前启动状态是否符合预期
				if (status.PowerSwitch == targetState)
				{
					_logger.LogInformation($"TCU {tcuId} 启动信号已达到目标状态: {targetState}");
					return OperationResult.Ok($"TCU启动信号已达到目标状态: {targetState}");
				}

				await Task.Delay(1000); // 检查间隔
			}

			_logger.LogWarning($"等待TCU {tcuId} 启动信号达到 {targetState} 超时");
			return OperationResult.Fail($"等待TCU启动信号超时（{timeoutMs}ms）");
		}

		/// <summary>
		/// 操作油浴盖
		/// </summary>
		/// <param name="open">是否打开盖子</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> OperateOilBathCoverAsync(bool open)
		{
			try
			{
				_logger.LogInformation($"开始{(open ? "打开" : "关闭")}油浴盖");

				// 这里简化处理，实际可能需要控制电机、气缸或其他执行元件
				// 假设这里有一个控制油浴盖的DO信号
				await ExecuteSequentialAsync(
					("油浴盖子方向", "油浴锅", () => _deviceStatusService.SetDOSignalStateAsync(DOSignalId.PushRodExtendDirection, !open)),
					("油浴盖子启动", "油浴锅", () => _deviceStatusService.SetDOSignalStateAsync(DOSignalId.PushRodExtendControl, open)),
					("等待盖子信号", "油浴锅", () => WaitForSignalCombinationAsync(
						new Dictionary<DISignalId, bool> { { DISignalId.PushRodExtendLimitSensor, open },
														   { DISignalId.PushRodRetractLimitSensor, !open } },
						30000))
				);
				return OperationResult.Ok($"油浴盖{(open ? "打开" : "关闭")}成功");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"操作油浴盖时发生异常");
				return OperationResult.Fail($"操作油浴盖时发生异常: {ex.Message}");
			}
		}

		#endregion

		#region 恢复方法

		/// <summary>
		/// 从物料准备阶段错误恢复
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <returns>恢复结果</returns>
		private async Task<(bool succeeded, string message)> RecoverFromMaterialPreparationErrorAsync(Experiment experiment)
		{
			try
			{
				// 实现特定阶段的恢复逻辑
				switch (experiment.CurrentSubStage)
				{
					//case ExperimentSubStage.LoadingMaterials:
					//	// 尝试重新加载物料
					//	await _deviceService.SetDeviceModeAsync(DeviceEnums.DeviceMode.SingleMachineAutomatic);
					//	// 具体恢复步骤...
					//	return (true, "成功重新开始物料加载");

					//case ExperimentSubStage.ScanningMaterials:
					//	// 尝试重新扫码
					//	// 具体恢复步骤...
					//	return (true, "成功重新扫描物料");

					// 其他子阶段恢复逻辑...

					default:
						return (false, "无法恢复未知子阶段的错误");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"尝试恢复实验 {experiment.ExperimentId} 物料准备阶段错误时发生异常");
				return (false, $"恢复过程中发生异常: {ex.Message}");
			}
		}

		/// <summary>
		/// 从加热阶段错误恢复
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <returns>恢复结果</returns>
		private async Task<(bool succeeded, string message)> RecoverFromHeatingErrorAsync(Experiment experiment)
		{
			// 实现加热阶段的恢复逻辑
			return (false, "加热阶段恢复功能尚未实现");
		}

		/// <summary>
		/// 从旋蒸阶段错误恢复
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <returns>恢复结果</returns>
		private async Task<(bool succeeded, string message)> RecoverFromRotaryEvaporationErrorAsync(Experiment experiment)
		{
			// 实现旋蒸阶段的恢复逻辑
			return (false, "旋蒸阶段恢复功能尚未实现");
		}

		/// <summary>
		/// 从收集阶段错误恢复
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <returns>恢复结果</returns>
		private async Task<(bool succeeded, string message)> RecoverFromCollectionErrorAsync(Experiment experiment)
		{
			// 实现收集阶段的恢复逻辑
			return (false, "收集阶段恢复功能尚未实现");
		}

		/// <summary>
		/// 从清洗阶段错误恢复
		/// </summary>
		/// <param name="experiment">实验</param>
		/// <returns>恢复结果</returns>
		private async Task<(bool succeeded, string message)> RecoverFromCleaningErrorAsync(Experiment experiment)
		{
			// 实现清洗阶段的恢复逻辑
			return (false, "清洗阶段恢复功能尚未实现");
		}

		#endregion

		#region 机械手操作方法实现


		/// <summary>
		/// 安装旋蒸瓶
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InstallRotaryEvaporationFlaskAsync(ItemType itemType, ushort pickPosition, ushort placePosition)
		{
			_logger.LogInformation($"开始安装旋蒸瓶");

			try
			{
				// 1、电机归位，并行操作
				await ExecuteParallelAsync(
					 ("移动到上升位置", "旋蒸升降电机", () => _motorControlService.MoveToPositionAsync("RotovapLiftMotor", "上升位置")),
					 ("移动到安装位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", "安装位"))
				);

				// 2、油浴锅归位，顺序操作
				await ExecuteSequentialAsync(
					//("打开油浴锅盖", "油浴锅", () => OperateOilBathCoverAsync(true)),
					("移动到收回位置", "油浴锅电机", () => _motorControlService.MoveToPositionAsync("OilBathMotor", "收回位置"))
				);


				var robotPickTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PickFromShelf_Bottle,
					BottleType = (ushort)itemType,
					Position = pickPosition
				};
				robotPickTaskSendDto.BottleType += 1;


				// 3、等待机器人空闲,并发送取瓶任务
				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					("发送取旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
					("执行取旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromShelf_Bottle + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				);

				var robotPlaceTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PlaceToRotaryStation,
					BottleType = (ushort)itemType,
					Position = placePosition
				};
				robotPlaceTaskSendDto.BottleType += 1;

				// 4、等待机器人空闲,并发送放瓶任务
				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					("发送安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人移动至旋蒸瓶安装位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000)),
					("旋紧旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", -600, 800, 50000, 30)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToRotaryStation + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				);

				//记录旋紧后角度
				var actStatus = await _motorControlService.GetMotorStatusAsync("RotovapRotaryMotor");
				_rotaryBottleTightenAngle = actStatus.Actual_P;

				//5、油浴锅移动至工作位，打开冷凝开关阀，关闭排冷凝液两通阀，关闭冷凝液回收两通阀，旋蒸瓶下降，旋转，油浴锅关盖
				//下降位置
				var downPosition = _rotaryBottleType == ItemType.Rotovap_500ml ? "500ml浸入位置" : "1000ml浸入位置";
				await ExecuteSequentialAsync(
					("移动到工作位", "油浴锅电机", () => _motorControlService.MoveToPositionAsync("OilBathMotor", "工作位置")),
					//("打开冷凝开关阀", "冷凝开关阀电机", () => _motorControlService.MoveToPositionAsync("CondenserValveMotor", "打开位置")),
					("关闭排冷凝液两通阀", "排冷凝液两通阀", () => SwitchValveAsync(DOSignalId.ExhaustCondensateLiquidValve, false, 1000)),
					("关闭冷凝液回收两通阀", "冷凝液回收两通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleValve, false, 1000)),
					("旋蒸瓶下降", "旋蒸升降电机", () => _motorControlService.MoveToPositionAsync("RotovapLiftMotor", downPosition)),
					("旋蒸瓶旋转", "旋蒸旋转电机", () => _motorControlService.JogPlusAsync("RotovapRotaryMotor", _rotarySpeed))//,
					//("关闭油浴锅盖", "油浴锅", () => OperateOilBathCoverAsync(false))
				);

				_logger.LogInformation("旋蒸瓶安装准备工作完成");
				return OperationResult.Ok("旋蒸瓶安装准备完成");
			}
			catch (Exception ex)
			{
				string errorMessage = $"安装旋蒸瓶过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);

				return OperationResult.Fail(errorMessage);
			}
		}

		/// <summary>
		/// 搬运瓶子至工作站
		/// </summary>
		/// <param name="itemType">瓶子类型</param>
		/// <param name="functionType">功能分类  
		/// FunctionType.Centrifuge_Empty 空离心瓶
		/// FunctionType.Centrifuge_To_Rotovap 原料离心瓶
		/// FunctionType.Centrifuge_Condensate_Collection 冷凝液收集离心瓶
		/// FunctionType.Centrifuge_Residue_Collection 旋蒸残液收集离心瓶
		/// FunctionType.Centrifuge_Wash_Liquid 洗液离心瓶 </param>
		/// <param name="sourcePosition">货架源位置 </param>
		/// <param name="targetPosition">目标位置 3- 抽液位 4-收集位</param>
		/// <param name="openCap">是否要开盖</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> TransportVialToWorkstationAsync(
			ItemType itemType,
			FunctionType functionType,
			ushort sourcePosition,
			ushort targetPosition,
			bool openCap = false
		)
		{
			string functionTypeStr = functionType.ToString();
			string targetPositionStr = targetPosition == 3 ? "抽液位" : "收集位";
			string actionStr = targetPosition == 3 ? "抽液" : "收集";

			_logger.LogInformation($"开始搬运{functionTypeStr}至{targetPositionStr}");

			try
			{
				if (openCap)
				{
					// 1、开关盖电机归位，并行操作
					await ExecuteParallelAsync(
						 ("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置")),
					 	 ("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
						 ("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
					);
				}

				if (targetPosition == 3)
				{
					// 2、抽液平台电机上升，并行操作
					await ExecuteParallelAsync(
						 ("移动到上升位置", "工作台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "上升位置"))//,
																																	//("初始位置", "洗液槽电机", () => _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置"))
					);
				}
				else if (targetPosition == 4)
				{
					// 2、收集平台电机上升，并行操作
					await ExecuteParallelAsync(
						 ("移动到上升位置", "工作台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "上升位置")),
						 ("移动到上升位置", "工作台取样针升降电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidLiftMotor", "上升位置"))//,
																																   //("初始位置", "洗液槽电机", () => _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置"))
					);
					// 3、取样针旋转电机归位
					await ExecuteSequentialAsync(
						 ("旋转到初始位置", "工作台取样针旋转电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidRotateMotor", "初始位置"))
					);
				}

				// 4、等待机器人空闲,并发送取瓶任务

				var robotPickTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PickFromShelf_Bottle,
					BottleType = (ushort)itemType,
					Position = sourcePosition
				};
				robotPickTaskSendDto.BottleType += 1;

				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					($"发送取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
					($"执行取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromShelf_Bottle + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

				);

				//5、等待机器人空闲,并发送放瓶任务
				var robotPlaceTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PlaceToWorkStation,
					BottleType = (ushort)itemType,
					Position = targetPosition
				};
				robotPlaceTaskSendDto.BottleType += 1;

				if (openCap)
				{
					await ExecuteSequentialAsync(
						("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
						($"发送放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
						($"执行放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
						("等待机器人到开盖位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000))
					);

					await ExecuteSequentialAsync(
						("移动到夹紧位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "夹紧位置")),
						("移动到夹紧位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "夹紧位置"))
					);

					await ExecuteSequentialAsync(
						("发送机器人继续执行信号——松开去夹盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人夹到盖子", "机器人", () => WaitForRobotSignalAsync(1, 2, 1200000)),
						("开盖", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "旋开位置")),
						("发送机器人继续执行信号——放盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 2, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人夹瓶身到位", "机器人", () => WaitForRobotSignalAsync(1, 3, 1200000))
					);

					await ExecuteParallelAsync(
						("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
						("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
					);

					await ExecuteSequentialAsync(
						("发送机器人继续执行信号——可取走至抽液平台", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 3, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToWorkStation + 1000, 1200000)),
					    ("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					    ("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0)),
						("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置"))
					);
				}
				else
				{
					// 4、等待机器人空闲,并发送任务,等待机器人到开盖位,移动到夹紧位置,开盖
					await ExecuteSequentialAsync(
						("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
						($"发送放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
						($"执行放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
						("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToWorkStation + 1000, 1200000)),
						("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
					);

				}

				// 5、根据目标位置标记工作台占用状态
				if (targetPosition == 3)
				{
					_isExtractLiquidOccupy = true;
				}
				else if (targetPosition == 4)
				{
					_isCollectLiquidOccupy = true;
				}

				_logger.LogInformation($"搬运{functionTypeStr}至{targetPositionStr}完成");
				return OperationResult.Ok($"搬运{functionTypeStr}至{targetPositionStr}完成");
			}
			catch (Exception ex)
			{
				string errorMessage = $"搬运{functionTypeStr}至{targetPositionStr}过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);

				return OperationResult.Fail(errorMessage);
			}
		}


		/// <summary>
		/// 从工作站退回瓶子至货架
		/// </summary>
		/// <param name="itemType">瓶子类型</param>
		/// <param name="functionType">功能分类</param>
		/// <param name="sourcePosition">源位置 3- 抽液位 4-收集位</param>
		/// <param name="targetPosition">货架目标位置</param>
		/// <param name="closeCap">是否关盖</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ReturnVialToShelfAsync(
			ItemType itemType,
			FunctionType functionType,
			ushort sourcePosition,
			ushort targetPosition,
			bool closeCap = false
		)
		{
			string functionTypeStr = functionType.ToString();
			string sourcePositionStr = sourcePosition == 3 ? "抽液位" : "收集位";
			string actionStr = sourcePosition == 3 ? "抽液" : "收集";

			_logger.LogInformation($"领域层: 开始从{sourcePositionStr}退回{functionTypeStr}至货架");
			try
			{
				if (closeCap)
				{
					// 1、开关盖电机归位，并行操作
					await ExecuteParallelAsync(
						("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置")),
						("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
						("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
					);
				}

				if (sourcePosition == 3)
				{
					// 2、抽液平台电机上升，并行操作
					await ExecuteParallelAsync(
						 ("移动到上升位置", "工作台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "上升位置"))//,
																																	//("初始位置", "洗液槽电机", () => _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置"))
					);
				}
				else if (sourcePosition == 4)
				{
					// 2、收集平台电机上升，并行操作
					await ExecuteParallelAsync(
						 ("移动到上升位置", "工作台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "上升位置")),
						 ("移动到上升位置", "工作台取样针升降电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidLiftMotor", "上升位置"))//,
																																   //("初始位置", "洗液槽电机", () => _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置"))
					);
					// 3、取样针旋转电机归位
					await ExecuteSequentialAsync(
						 ("旋转到初始位置", "工作台取样针旋转电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidRotateMotor", "初始位置"))
					);
				}

				//4.等待机器人空闲发送取瓶任务

				var robotPickTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PickFromWorkStation,
					BottleType = (ushort)itemType,
					Position = sourcePosition
				};
				robotPickTaskSendDto.BottleType += 1;

				if (closeCap)
				{
					await ExecuteSequentialAsync(
						("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
						($"发送取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
						($"执行取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
						("等待机器人到关盖位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000))
					);

					await ExecuteSequentialAsync(
						("移动到夹紧位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "夹紧位置")),
						("移动到夹紧位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "夹紧位置"))
					);

					await ExecuteSequentialAsync(
						("发送机器人继续执行信号——松开去取盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人取盖到达关盖位", "机器人", () => WaitForRobotSignalAsync(1, 2, 1200000)),
						("关盖", "开关盖旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("BottleRotateMotor", 800, 500, 60000, 30)),
						("发送机器人继续执行信号——夹瓶身", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 2, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人夹瓶身到位", "机器人", () => WaitForRobotSignalAsync(1, 3, 1200000))
					);

					await ExecuteParallelAsync(
						("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
						("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
					);

					await ExecuteSequentialAsync(
						("发送机器人继续执行信号——可取走至抽液平台", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 3, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromWorkStation + 1000, 1200000)),
						("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0)),
						("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置"))
					);
				}
				else
				{
					//4.等待机器人空闲发送取瓶任务
					await ExecuteSequentialAsync(
						("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
						($"发送取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
						($"执行取{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
						("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromWorkStation + 1000, 1200000)),
						("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
						("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
					);
				}

				//5、等待机器人空闲发送放瓶任务
				var robotPlaceTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PlaceToShelf_Bottle,
					BottleType = (ushort)itemType,
					Position = targetPosition
				};
				robotPlaceTaskSendDto.BottleType += 1;

				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					($"发送放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
					($"执行放{functionTypeStr}任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToShelf_Bottle + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				);

				// 根据源位置更新工作台占用状态
				if (sourcePosition == 3)
				{
					_isExtractLiquidOccupy = false;
				}
				else if (sourcePosition == 4)
				{
					_isCollectLiquidOccupy = false;
				}

				_logger.LogInformation($"从{sourcePositionStr}退回{functionTypeStr}至货架完成");
				return OperationResult.Ok($"从{sourcePositionStr}退回{functionTypeStr}至货架完成");
			}
			catch (Exception ex)
			{
				string errorMessage = $"从{sourcePositionStr}退回{functionTypeStr}至货架过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);
				return OperationResult.Fail(errorMessage);
			}
		}

		/// <summary>
		/// 更换夹爪
		/// </summary>
		/// <param name="targetGripper">目标夹爪类型</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ChangeGripperAsync(int targetGripper)
		{
			_logger.LogInformation($"领域层: 开始更换夹爪: {targetGripper}");

			try
			{
				// 模拟更换夹爪
				// 在实际应用中，这里应该调用设备控制服务执行夹爪更换

				await Task.Delay(300); // 模拟异步操作

				_logger.LogInformation($"领域层: 夹爪更换完成: {targetGripper}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"领域层: 更换夹爪时发生错误: {targetGripper}");
				return new OperationResult
				{
					Success = false,
					Message = $"更换夹爪时发生错误: {ex.Message}"
				};
			}
		}


		#endregion

		#region 液体处理方法实现

		/// <summary>
		/// 旋蒸原液输送流程
		/// </summary>
		/// <param name="pumpVolume">打液体积</param>
		/// <param name="isFirstPump">是否是第一次打液</param>
		/// <param name="isCheckLiquidLevel">是否看液位</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> PumpMaterialLiquidProcessAsync(double pumpVolume, bool isFirstPump, bool isCheckLiquidLevel)
		{
			try
			{
				//1.下插抽液针
				await ExecuteSequentialAsync(
					("移动到下插位置", "抽液平台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "下降位置离心瓶"))
				);

				var switchValve = _deviceManager.GetValve("Valve_COM8_0");

				//2.阀切换,破真空
				await ExecuteParallelAsync(
					("打开", "清洗三通阀1", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve1, true, 1000)),
					("打开", "清洗三通阀2", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve2, true, 1000)),
					("切到通道3", "切换阀", () => switchValve.SwitchToChannelAsync(3)),
					("打开", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, true, 1000))//,
																											   //("破真空", "冷凝管", () => BreakVacuumAsync())
				);

				//3.原液输送
				await ExecuteSequentialAsync(
					("原液输送", "旋蒸补液泵", () => PumpMaterialLiquidAsync(pumpVolume, isFirstPump, isCheckLiquidLevel)),
					("关闭", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, false, 1000))
				);

				_logger.LogInformation($"液体泵送完成");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"液体泵送时发生错误");
				return new OperationResult
				{
					Success = false,
					Message = $"液体泵送时发生错误: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 旋蒸原液打液
		/// </summary>
		/// <param name="pumpVolume">打液体积</param>
		/// <param name="isFirstPump">是否首次打液</param>
		/// <param name="isCheckLiquidLevel">是否需要在方法内部监控液位，设为false表示由MonitorAndReplenishLiquidAsync方法统一监控</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> PumpMaterialLiquidAsync(double pumpVolume, bool isFirstPump, bool isCheckLiquidLevel)
		{
			try
			{
				_logger.LogInformation($"开始旋蒸原液打液: 旋蒸瓶类型={_rotaryBottleType}, 打液量={pumpVolume}ml, 首次打液={isFirstPump}, 监控液位={isCheckLiquidLevel}");

				// 更新状态标志
				_isCurrentMaterialLiquidFinished = false;

				// 使用可暂停的打液方法   200rpm/min=118ml/min   ->  118/200=0.59ml/r
				var pumpResult = await ExecutePausableDispensingAsync(
					"RotovapPump",       // 电机ID
					pumpVolume,          // 打液量
					0.59,                   // 转换因子
					400,                 // 打液速度
					isCheckLiquidLevel   // 是否在本方法内监控液位（由外部决定）
				);

				// 根据打液结果和瓶子类型更新打液状态
				if (pumpResult.Success)
				{
					if (isFirstPump)
					{
						// 1000ml旋蒸瓶默认打完，500ml旋蒸瓶默认打完350ml,未打完
						_isCurrentMaterialLiquidFinished = _rotaryBottleType == ItemType.Rotovap_1000ml;

						if (!_isCurrentMaterialLiquidFinished)
						{
							_unPumpedLiquidVolume = _centrifugeBottleVolume - pumpVolume;
							_logger.LogInformation($"首次打液完成，未打完液体量: {_unPumpedLiquidVolume}ml");
						}
						else
						{
							_logger.LogInformation("首次打液完成，所有液体已打完");
						}
					}
					else // 补液
					{
						// 记录未打完液体
						if (!_isCurrentMaterialLiquidFinished)
						{
							_unPumpedLiquidVolume -= pumpVolume;

							// 如果未打液量小于等于0，则认为液体已打完
							if (_unPumpedLiquidVolume <= 0)
							{
								_isCurrentMaterialLiquidFinished = true;
								_logger.LogInformation("补液完成，所有液体已打完");
							}
							else
							{
								_logger.LogInformation($"补液完成，剩余未打液体量: {_unPumpedLiquidVolume}ml");
							}
						}
					}

					return OperationResult.Ok($"原液输送完成，已打液: {pumpVolume}ml");
				}
				else
				{
					_logger.LogWarning($"原液输送未完成: {pumpResult.Message}");
					return pumpResult; // 返回原始错误
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"旋蒸原液打液时发生错误");
				return OperationResult.Fail($"旋蒸原液打液时发生错误: {ex.Message}");
			}
		}


		/// <summary>
		/// 阀门切换
		/// </summary>
		/// <param name="valveDOId">阀DOID</param>
		/// <param name="open">是否打开</param>
		/// <param name="delayTime">延迟时间</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> SwitchValveAsync(DOSignalId valveDOId, bool open, int delayTime)
		{
			try
			{
				_logger.LogInformation($"阀切换");
				_deviceStatusService.SetDOSignalStateAsync(valveDOId, open);
				await Task.Delay(delayTime);
				_logger.LogInformation($"阀门切换完成: {valveDOId}, 状态: {open}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"阀门切换时发生错误: {valveDOId}");
				return new OperationResult
				{
					Success = false,
					Message = $"阀门切换时发生错误: {ex.Message}"
				};
			}
		}

		#endregion

		#region 工作站操作实现

		/// <summary>
		/// 旋蒸瓶安装
		/// </summary>
		/// <param name="flaskParams">旋蒸瓶参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> MountEvaporationFlaskAsync(FlaskParams flaskParams)
		{
			_logger.LogInformation($"领域层: 开始旋蒸瓶安装: {flaskParams.FlaskId}");

			try
			{
				// 模拟旋蒸瓶安装
				// 在实际应用中，这里应该调用设备控制服务执行旋蒸瓶安装

				await Task.Delay(300); // 模拟异步操作

				_logger.LogInformation($"领域层: 旋蒸瓶安装完成: {flaskParams.FlaskId}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"领域层: 旋蒸瓶安装时发生错误: {flaskParams.FlaskId}");
				return new OperationResult
				{
					Success = false,
					Message = $"旋蒸瓶安装时发生错误: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 旋蒸瓶拆卸
		/// </summary>
		/// <param name="itemType">瓶子类型</param>
		/// <param name="pickPosition">取瓶位置 旋蒸工作台</param>
		/// <param name="placePosition">放瓶位置 XX-货架 3-工作台抽液位</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> DismountEvaporationFlaskAsync(ItemType itemType, ushort pickPosition, ushort placePosition)
		{
			try
			{
				// 确定拆卸目标位置
				string targetPositionStr = placePosition == 3 ? "工作台抽取位" : "货架";
				_logger.LogInformation($"旋蒸瓶拆卸目标位置: {targetPositionStr}");

				// 1. 停止旋转，破真空
				await ExecuteParallelAsync(
					("停止旋转", "旋蒸旋转电机", () => _motorControlService.StopMotorAsync("RotovapRotaryMotor"))//,
																									   //("破真空", "冷凝管", () => BreakVacuumAsync())
				);

				//如果目标位置是工作台抽液位，则提升抽液针
				if (placePosition == 3)
				{
					//工作台抽液针提升
					await ExecuteSequentialAsync(
						("上升位置", "抽液平台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "上升位置"))//,
																																 //("初始位置", "洗液槽电机", () => _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置"))
					);
				}

				// 2. 回归到安装位 _rotaryBottleTightenAngle
				//先获取当前角度

				var actStatus = await _motorControlService.GetMotorStatusAsync("RotovapRotaryMotor");
				var currentAngle = actStatus.Actual_P;
				//计算回归角度,会到离当前位置最近的角度_rotaryBottleTightenAngle
				var currentFullRotations = Math.Floor(currentAngle / 360.0);
				var targetAngle = (currentFullRotations * 360.0) + (_rotaryBottleTightenAngle % 360.0);


				await ExecuteSequentialAsync(
					("回零", "旋蒸旋转电机", () => _motorControlService.HomeMotorAsync("RotovapRotaryMotor")),
					("回归到卸载位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", "卸载位"))
				);



				// 3. 油浴锅归位，旋蒸瓶提升到安全位置
				await ExecuteSequentialAsync(
					//("打开油浴锅盖", "油浴锅", () => OperateOilBathCoverAsync(true)),
					("旋蒸瓶上升", "旋蒸升降电机", () => _motorControlService.MoveToPositionAsync("RotovapLiftMotor", "上升位置")),
					("移动到收回位置", "油浴锅电机", () => _motorControlService.MoveToPositionAsync("OilBathMotor", "收回位置"))
				);

				// 4. 等待机器人空闲并发送拆卸旋蒸瓶任务
				var robotPickTaskSendDto = new RobotTaskSendDto
				{
					TaskType = TaskType.PickFromRotaryStation,
					BottleType = (ushort)itemType,
					Position = pickPosition
				};
				robotPickTaskSendDto.BottleType += 1;

				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					("发送拆卸旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
					("执行拆卸旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人夹住旋蒸瓶", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000)),
					("松开旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", 600, 800, 50000, 30)),
					("发送机器人继续执行信号——取走旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromRotaryStation + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0)),
					("松开旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.HomeMotorAsync("RotovapRotaryMotor"))

				);

				//5、等待机器人空闲，发送放瓶任务
				var robotPlaceTaskSendDto = new RobotTaskSendDto
				{
					TaskType = placePosition == 3 ? TaskType.PlaceToWorkStation : TaskType.PlaceToShelf_Bottle,
					BottleType = (ushort)itemType,
					Position = placePosition
				};
				robotPlaceTaskSendDto.BottleType += 1;

				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
					("发送放瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
					("执行放瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)robotPlaceTaskSendDto.TaskType + 1000, 1200000)),
					("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
					("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				);


				_logger.LogInformation($"旋蒸瓶拆卸完成，已拆卸至{placePosition}");
				return OperationResult.Ok($"旋蒸瓶拆卸完成，已拆卸至{placePosition}");
			}
			catch (Exception ex)
			{
				string errorMessage = $"拆卸旋蒸瓶过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);

				return OperationResult.Fail(errorMessage);
			}
		}

		/// <summary>
		/// 插管操作
		/// </summary>
		/// <param name="tubeParams">插管参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InsertTubeAsync(TubeParams tubeParams)
		{
			_logger.LogInformation($"领域层: 开始插管操作: {tubeParams.VialId}, 类型: {tubeParams.TubeType}");

			try
			{
				// 模拟插管操作
				// 在实际应用中，这里应该调用设备控制服务执行插管操作

				await Task.Delay(200); // 模拟异步操作

				_logger.LogInformation($"领域层: 插管操作完成: {tubeParams.VialId}, 类型: {tubeParams.TubeType}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"领域层: 插管操作时发生错误: {tubeParams.VialId}");
				return new OperationResult
				{
					Success = false,
					Message = $"插管操作时发生错误: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 撤管操作
		/// </summary>
		/// <param name="tubeParams">撤管参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> WithdrawTubeAsync(TubeParams tubeParams)
		{
			_logger.LogInformation($"领域层: 开始撤管操作: {tubeParams.VialId}, 类型: {tubeParams.TubeType}");

			try
			{
				// 模拟撤管操作
				// 在实际应用中，这里应该调用设备控制服务执行撤管操作

				await Task.Delay(200); // 模拟异步操作

				_logger.LogInformation($"领域层: 撤管操作完成: {tubeParams.VialId}, 类型: {tubeParams.TubeType}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"领域层: 撤管操作时发生错误: {tubeParams.VialId}");
				return new OperationResult
				{
					Success = false,
					Message = $"撤管操作时发生错误: {ex.Message}"
				};
			}
		}

		#endregion

		#region 旋蒸参数控制实现

		/// <summary>
		/// 设置加热参数
		/// </summary>
		/// <param name="heatingParams">加热参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> SetHeatingParametersAsync(HeatingParams heatingParams)
		{
			_logger.LogInformation($"领域层: 设置加热参数: 目标温度 {heatingParams.TargetTemperature}°C, 加热速率 {heatingParams.HeatingRate}°C/min");

			try
			{
				throw new NotImplementedException();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域层: 设置加热参数时发生错误");
				return new OperationResult
				{
					Success = false,
					Message = $"设置加热参数时发生错误: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 设置真空参数
		/// </summary>
		/// <param name="vacuumParams">真空参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> SetVacuumParametersAsync(VacuumParams vacuumParams)
		{
			_logger.LogInformation($"领域层: 设置真空参数: 目标真空度 {vacuumParams.TargetVacuum} mbar, 真空速率 {vacuumParams.VacuumRate} mbar/min");

			try
			{
				throw new NotImplementedException();
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域层: 设置真空参数时发生错误");
				return new OperationResult
				{
					Success = false,
					Message = $"设置真空参数时发生错误: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 设置旋转参数
		/// </summary>
		/// <param name="rotParams">旋转参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> SetRotationParametersAsync(RotationParams rotParams)
		{
			_logger.LogInformation($"领域层: 设置旋转参数: 目标转速 {rotParams.TargetSpeed} rpm, 加速度 {rotParams.Acceleration} rpm/s");

			throw new NotImplementedException();
		}

		#endregion

		#region 清洗方法实现

		/// <summary>
		/// 系统清洗
		/// </summary>
		/// <param name="cleaningParams">清洗参数</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> CleanSystemAsync(CleaningParams cleaningParams)
		{
			_logger.LogInformation($"领域层: 开始系统清洗: 类型: {cleaningParams.CleaningType}, 循环次数: {cleaningParams.CleaningCycles}");

			try
			{
				// 模拟系统清洗
				// 在实际应用中，这里应该调用设备控制服务执行系统清洗

				await Task.Delay(500); // 模拟异步操作

				_logger.LogInformation($"领域层: 系统清洗完成: 类型: {cleaningParams.CleaningType}");

				return new OperationResult { Success = true };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"领域层: 系统清洗时发生错误: 类型: {cleaningParams.CleaningType}");
				return new OperationResult
				{
					Success = false,
					Message = $"系统清洗时发生错误: {ex.Message}"
				};
			}
		}

		#endregion

		#region 设备控制方法实现

		/// <summary>
		/// 设置设备模式
		/// </summary>
		/// <param name="mode">设备模式</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> SetDeviceModeAsync(DeviceEnums.DeviceMode mode)
		{
			return await _deviceService.SetDeviceModeAsync(mode);
		}

		/// <summary>
		/// 获取设备状态
		/// </summary>
		/// <returns>设备状态</returns>
		public async Task<DeviceEnums.DeviceStatus> GetDeviceStatusAsync()
		{
			return await _deviceService.GetDeviceStatusAsync();
		}

		/// <summary>
		/// 执行紧急停止
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteEmergencyStopAsync()
		{
			throw new NotImplementedException();
			//try
			//{
			//	_logger.LogWarning("执行紧急停止操作");

			//	// 1. 停止所有电机
			//	var motorIds = await _motorControlService.GetAllMotorIdsAsync();
			//	foreach (var motorId in motorIds)
			//	{
			//		try
			//		{
			//			await _motorControlService.StopMotorAsync(motorId);
			//			_logger.LogInformation($"紧急停止: 已停止电机 {motorId}");
			//		}
			//		catch (Exception ex)
			//		{
			//			_logger.LogError(ex, $"紧急停止: 停止电机 {motorId} 时出错");
			//		}
			//	}

			//	// 2. 停止TCU设备
			//	try
			//	{
			//		var tcu = _deviceManager.GetTCU("TCU_502_1");
			//		if (tcu != null)
			//		{
			//			await tcu.PowerSwitchAsync(false);
			//			_logger.LogInformation("紧急停止: 已停止TCU设备");
			//		}
			//	}
			//	catch (Exception ex)
			//	{
			//		_logger.LogError(ex, "紧急停止: 停止TCU设备时出错");
			//	}

			//	// 3. 停止油浴锅
			//	try
			//	{
			//		var oilBath = _deviceManager.GetOilBath("OilBath_503_1");
			//		if (oilBath != null)
			//		{
			//			await oilBath.SetRunningStatusAsync(1); // 假设1是停止状态
			//			_logger.LogInformation("紧急停止: 已停止油浴锅");
			//		}
			//	}
			//	catch (Exception ex)
			//	{
			//		_logger.LogError(ex, "紧急停止: 停止油浴锅时出错");
			//	}

			//	// 4. 停止机器人(如果正在运行)
			//	try
			//	{
			//		if (_robotStatus.IsMoving || _robotTaskStatus.RobotProcessState != RobotProcessState.Idle)
			//		{
			//			var robot = _deviceManager.Robot;
			//			if (robot != null)
			//			{
			//				await robot.ExecuteStopTaskAsync();
			//				_logger.LogInformation("紧急停止: 已停止机器人动作");
			//			}
			//		}
			//	}
			//	catch (Exception ex)
			//	{
			//		_logger.LogError(ex, "紧急停止: 停止机器人时出错");
			//	}

			//	// 5. 重置所有DO信号到安全状态
			//	try
			//	{
			//		// 关闭所有阀门
			//		var doSignals = new DOSignalId[]
			//		{
			//			DOSignalId.CondenserWashLiquidValve,
			//			DOSignalId.EvaporateFlaskCleanValve,
			//			DOSignalId.OilBathCoverValve,
			//			DOSignalId.ProductCoverValve,
			//			DOSignalId.RotaryBottleValve,
			//			DOSignalId.VacuumValve
			//		};

			//		foreach (var signalId in doSignals)
			//		{
			//			await _deviceStatusService.SetDOSignalStateAsync(signalId, false);
			//			_logger.LogInformation($"紧急停止: 已关闭信号 {signalId}");
			//		}
			//	}
			//	catch (Exception ex)
			//	{
			//		_logger.LogError(ex, "紧急停止: 重置DO信号时出错");
			//	}

			//	_logger.LogWarning("紧急停止操作完成");
			//	return OperationResult.Ok("已执行紧急停止操作，所有设备已停止");
			//}
			//catch (Exception ex)
			//{
			//	_logger.LogError(ex, "执行紧急停止时发生未处理的错误");
			//	return OperationResult.Fail($"执行紧急停止时发生错误: {ex.Message}");
			//}
		}

		public async Task<OperationResult> ExecutePauseAsync()
		{
			try
			{
				//_logger.LogWarning("执行实验暂停操作...");

				//// 1. 停止所有电机运行，但不重置位置
				//var motorIds = _deviceManager.GetAllMotorIds();
				//foreach (var motorId in motorIds)
				//{
				//	try
				//	{
				//		var result = await _motorControlService.StopMotorAsync(motorId);
				//		_logger.LogInformation($"暂停电机 {motorId} 运行: {(result.Success ? "成功" : "失败")}");
				//	}
				//	catch (Exception ex)
				//	{
				//		_logger.LogError(ex, $"暂停电机 {motorId} 时发生错误: {ex.Message}");
				//	}
				//}

				//// 2. 暂停油浴锅加热，但保持通电状态
				//try
				//{
				//	var oilBathId = "OilBath_503_1"; // 主油浴锅ID
				//	if (_deviceManager.ContainsOilBath(oilBathId))
				//	{
				//		await _deviceManager.SetOilBathTemperatureAsync(oilBathId, 25); // 设置为安全温度
				//		_logger.LogInformation($"将油浴锅 {oilBathId} 温度设置为安全温度");
				//	}
				//}
				//catch (Exception ex)
				//{
				//	_logger.LogError(ex, $"暂停油浴锅时发生错误: {ex.Message}");
				//}

				//// 3. 暂停TCU，但保持通电状态
				//try
				//{
				//	var tcuId = "TCU_502_1"; // 主TCU ID
				//	if (_deviceManager.ContainsTCU(tcuId))
				//	{
				//		await _deviceManager.SetTCUTemperatureAsync(tcuId, 25); // 设置为安全温度
				//		_logger.LogInformation($"将TCU {tcuId} 温度设置为安全温度");
				//	}
				//}
				//catch (Exception ex)
				//{
				//	_logger.LogError(ex, $"暂停TCU时发生错误: {ex.Message}");
				//}

				//// 4. 暂停机器人当前任务，如果正在执行
				//try
				//{
				//	if (_robotStatus != null && (_robotStatus.IsMoving || !_robotStatus.IsIdle))
				//	{
				//		await _deviceManager.ExecuteStopTaskAsync();
				//		_logger.LogInformation("暂停机器人当前任务");
				//	}
				//}
				//catch (Exception ex)
				//{
				//	_logger.LogError(ex, $"暂停机器人任务时发生错误: {ex.Message}");
				//}

				//// 5. 关闭关键阀门，但不是所有阀门
				//var criticalValves = new List<DOSignalId>
				//{
				//	DOSignalId.Valve_VacuumMain,
				//	DOSignalId.Valve_NitrogenPurge
				//};

				//foreach (var signalId in criticalValves)
				//{
				//	try
				//	{
				//		var result = await _deviceManager.SetDOSignalStateAsync(signalId, false);
				//		_logger.LogInformation($"关闭阀门 {signalId}: {(result.Success ? "成功" : "失败")}");
				//	}
				//	catch (Exception ex)
				//	{
				//		_logger.LogError(ex, $"关闭阀门 {signalId} 时发生错误: {ex.Message}");
				//	}
				//}

				//// 6. 记录暂停事件到数据记录服务
				//if (_currentExperimentId.HasValue)
				//{
				//	try
				//	{
				//		await _dataRecordingService.RecordExperimentEventAsync(
				//			_currentExperimentId.Value,
				//			"实验暂停",
				//			"用户或系统触发了实验暂停操作");
				//	}
				//	catch (Exception ex)
				//	{
				//		_logger.LogError(ex, "记录暂停事件时发生错误");
				//	}
				//}

				//_logger.LogWarning("实验暂停操作完成 - 系统处于暂停状态，可以恢复操作");
				return OperationResult.Ok("实验已暂停，设备已安全停止");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "执行实验暂停操作时发生错误");
				return OperationResult.Fail($"暂停操作失败: {ex.Message}");
			}
		}

		/// <summary>
		/// 重置设备
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ResetDeviceAsync()
		{
			//return await _deviceService.ResetDeviceAsync();
			throw new NotImplementedException();
		}

		#endregion

		#region 工艺流程实现

		/// <summary>
		/// 执行物料&条件准备阶段
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteMaterialAndConditionPreparationAsync(Experiment experiment)
		{
			_logger.LogInformation($"开始执行实验 {experiment.ExperimentId} 的物料&条件准备阶段");

			// 更新实验阶段
			experiment.CurrentStage = ExperimentStage.MaterialAndConditionPreparation;

			// 只有在子阶段为NotStarted或为null时才初始化状态变量
			if (experiment.CurrentSubStage == ExperimentSubStage.NotStarted || experiment.CurrentSubStage == null)
			{
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				_currentVialIndex = 0;
				_currentProductIndex = 0;
				_productCount = experiment.ExecutionParameters.ProductParameters.Count;
				_materialVialCount = experiment.ExecutionParameters.MaterialLocations.Count;
				_isMultiVial = _materialVialCount > 1;
				_isExtractLiquidOccupy = false;
				_isCollectLiquidOccupy = false;
				_isLastMaterialVial = _isMultiVial ? false : true;
				_materialVialPositions = experiment.ExecutionParameters.MaterialLocations;
			}

			//更新产物当前参数
			UpdateProductCurrentParameters(experiment);

			// 触发阶段变更事件
			OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.MaterialAndConditionPreparation);
			OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.MaterialAndConditionPreparation, experiment.CurrentSubStage);

			try
			{
				_currentExperimentId = experiment.ExperimentId;
				_currentStage = ExperimentStage.MaterialAndConditionPreparation;
				_currentSubStage = experiment.CurrentSubStage;

				// 根据当前子阶段确定从哪里开始执行
				switch (experiment.CurrentSubStage)
				{
					case ExperimentSubStage.NotStarted:
						// 从头开始执行
						goto case ExperimentSubStage.ControllingOilBathTemperature;

					case ExperimentSubStage.ControllingOilBathTemperature:
						//1.控制油浴锅温度，控制冷凝器温度
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.ControllingOilBathTemperature,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在控制油浴锅温度");
								var oilBath = _deviceManager.GetOilBath("OilBath_503_1");
								await ExecuteSequentialAsync(
									("设定定制模式", "油浴锅", () => oilBath.SetControlModeAsync(0)),
									("设定温度", "油浴锅", () => oilBath.SetTemperatureAsync(_oilBathTemperature)),
									("启动加热", "油浴锅", () => oilBath.SetRunningStatusAsync(0)),
									("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
									("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

								);
							});
						goto case ExperimentSubStage.ControllingCondensationTemperature;

					case ExperimentSubStage.ControllingCondensationTemperature:
						//2.控制冷凝器温度
						//获取产品冷凝器温度
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.ControllingCondensationTemperature,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在控制冷凝器温度");
								//var tcu = _deviceManager.GetTCU("TCU_502_1");
								//await ExecuteSequentialAsync(
								//	("设定温度", "冷凝器", () => tcu.SetTemperatureAsync(_condenserTemperature)),
								//	("允许制冷", "冷凝器", () => tcu.AllowCoolingSwitchAsync(true)),
								//	("启动", "冷凝器", () => tcu.PowerSwitchAsync(true)),
								//	("等待TCU启动信号", "冷凝器", () => WaitForTCUStartSignalAsync("TCU_502_1", true, 30000))
								//);
							});
						goto case ExperimentSubStage.InstallingRotaryBottle;

					case ExperimentSubStage.InstallingRotaryBottle:
						//3.对接旋蒸瓶
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.InstallingRotaryBottle,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在对接旋蒸瓶");
								//准备搬运参数
								//获取旋蒸瓶的种类
								var rotaryBottleSize = experiment.ExecutionParameters.RotaryBottleType;
								_rotaryBottleType = rotaryBottleSize == RotaryBottleSize.RotaryBottle_500ml ?
									ItemType.Rotovap_500ml : ItemType.Rotovap_1000ml;
								//在货架上找到合适的旋蒸空瓶，IsReserved为1
								var availableRotaryBottleLocations = await _storageService.GetBottleLocationsByReservedStatusAsync(_rotaryBottleType, 1);

								var rotaryBottleLocation = availableRotaryBottleLocations.FirstOrDefault();
								_rotaryEmptyBottlePosition = rotaryBottleLocation.Position;

								// 将瓶子状态更新为已使用
								rotaryBottleLocation.UpdateIsReserved(2);
								await _storageService.UpdateShelfLocationAsync(rotaryBottleLocation);

								//安装旋蒸瓶
								await InstallRotaryEvaporationFlaskAsync(_rotaryBottleType, (ushort)_rotaryEmptyBottlePosition, 5);
							});
						goto case ExperimentSubStage.TransportingMaterialVial;

					case ExperimentSubStage.TransportingMaterialVial:
						//4.搬运物料瓶至抽液位
						if (!_isExtractLiquidOccupy)
						{
							await ExecuteSubStageAsync(
								experiment,
								ExperimentSubStage.TransportingMaterialVial,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在搬运物料瓶至抽液位");

								//获取物料瓶位置
								_materialCentrifugePosition = _materialVialPositions[_currentVialIndex];
								//根据位置号找瓶子
								var materialVialLocation = await _storageService.GetShelfLocationAsync(LocationCode.Shelf, _materialCentrifugePosition);
								//将瓶子状态跟新
								materialVialLocation.UpdateIsReserved(2);
								await _storageService.UpdateShelfLocationAsync(materialVialLocation);

								//搬运物料瓶至抽液平台
								await TransportVialToWorkstationAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_To_Rotovap, (ushort)_materialCentrifugePosition, 3, true);
							});
						}
						goto case ExperimentSubStage.PumpingLiquid;

					case ExperimentSubStage.PumpingLiquid:
						//5.打液
						await ExecuteSubStageAsync(
							experiment,
									ExperimentSubStage.PumpingLiquid,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在打液");
								//泵送原料液体
								//旋蒸瓶类型判断打液量
								var pumpVolume = _rotaryBottleType == ItemType.Rotovap_500ml ? _rotaryPumpVolume500ml : _rotaryPumpVolume1000ml;
								await PumpMaterialLiquidProcessAsync(pumpVolume, true, false);
							});

						// 判断是否需要返回原料离心瓶
						if (_isCurrentMaterialLiquidFinished && _isExtractLiquidOccupy)
						{
							goto case ExperimentSubStage.ReturningMaterialVial;
						}
						else
						{
							goto case ExperimentSubStage.TransportingEmptyCentrifugeToCollection;
						}

					case ExperimentSubStage.ReturningMaterialVial:
						//6.返回原料离心瓶
						if (_isCurrentMaterialLiquidFinished && _isExtractLiquidOccupy)
						{
							await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.ReturningMaterialVial,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在返回原料离心瓶");

								//返回原料离心瓶
								await ReturnVialToShelfAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_To_Rotovap, 3, (ushort)_materialCentrifugePosition, true);
							});
						}
						goto case ExperimentSubStage.TransportingEmptyCentrifugeToCollection;

					case ExperimentSubStage.TransportingEmptyCentrifugeToCollection:
						//7.搬运空离心瓶至收集位
						if (_isCondensateLiquidCollected || _isCondensateLiquidSampled)
						{
							await ExecuteSubStageAsync(
								experiment,
								ExperimentSubStage.TransportingEmptyCentrifugeToCollection,
								async () =>
								{
									_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在搬运空离心瓶至收集位");
									//获取空离心瓶位置
									var emptyCentrifugeLocations = await _storageService.GetBottleLocationsByReservedStatusAsync(ItemType.CentrifugeBottle_500ml, 1);
									//获取空离心瓶位置
									var emptyCentrifugeLocation = emptyCentrifugeLocations.FirstOrDefault();
									_condenserLiquidCollectionPosition = emptyCentrifugeLocation.Position;
									//将瓶子状态跟新
									emptyCentrifugeLocation.UpdateIsReserved(2);
									await _storageService.UpdateShelfLocationAsync(emptyCentrifugeLocation);
									//定义机器人任务 - 从货架取空离心瓶到收集位

									//搬运空离心瓶至收集位
									await TransportVialToWorkstationAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_Empty, (ushort)_condenserLiquidCollectionPosition, 2, true);
								});
						}
						goto case ExperimentSubStage.WaitingOilBathTemperatureAndTCUTemperature;


					case ExperimentSubStage.WaitingOilBathTemperatureAndTCUTemperature:
						//8.等待油浴锅温度和TCU温度
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.WaitingOilBathTemperatureAndTCUTemperature,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在等待油浴锅温度和TCU温度");
								//等待油浴锅温度和TCU温度
								await ExecuteParallelAsync(
									("等待油浴锅温度", "油浴锅", () => WaitForOilBathTemperatureAsync("OilBath_503_1", _oilBathTemperature, 1.0, 1800000))//,
																																				//("等待TCU温度", "冷凝器", () => WaitForTCUTemperatureAsync("TCU_502_1", _condenserTemperature, 1.0, 1800000))
								);
							});

						goto case ExperimentSubStage.Completed;

					case ExperimentSubStage.Completed:
						// 物料&条件准备阶段完成
						experiment.CurrentSubStage = ExperimentSubStage.Completed;
						_logger.LogInformation($"实验 {experiment.ExperimentId} 的物料&条件准备阶段已完成");
						break;

					default:
						_logger.LogWarning($"未知的子阶段: {experiment.CurrentSubStage}，将从头开始执行物料&条件准备阶段");
						experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
						goto case ExperimentSubStage.NotStarted;
				}

				return new OperationResult { Success = true, Message = "物料&条件准备阶段完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行实验 {experiment.ExperimentId} 的物料&条件准备阶段时发生未处理的错误");
				return await HandleExperimentErrorAsync(experiment, ex.Message);
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		/// <summary>
		/// 执行旋蒸阶段
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteRotaryEvaporationAsync(Experiment experiment)
		{
			_logger.LogInformation($"开始执行实验 {experiment.ExperimentId} 的旋蒸阶段");

			// 更新实验阶段
			experiment.CurrentStage = ExperimentStage.RotaryEvaporation;

			// 只有在子阶段为NotStarted或为null时才初始化状态变量
			if (experiment.CurrentSubStage == ExperimentSubStage.NotStarted || experiment.CurrentSubStage == null)
			{
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
				_refillSituation = 0;
			}

			// 触发阶段变更事件
			OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.RotaryEvaporation);
			OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.RotaryEvaporation, experiment.CurrentSubStage);

			try
			{
				_currentExperimentId = experiment.ExperimentId;
				_currentStage = ExperimentStage.RotaryEvaporation;
				_currentSubStage = experiment.CurrentSubStage;

				// 根据当前子阶段确定从哪里开始执行
				switch (experiment.CurrentSubStage)
				{
					case ExperimentSubStage.NotStarted:
						// 从头开始执行
						goto case ExperimentSubStage.VacuumBuilding;

					case ExperimentSubStage.VacuumBuilding:
						// 1. 建立真空
						await ExecuteSubStageAsync(
					experiment,
							ExperimentSubStage.VacuumBuilding,
					async () =>
					{
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在建立真空");

						//下降收集插针(如果有瓶子的话)
						if (_isCollectLiquidOccupy)
							await ExecuteSequentialAsync(
								("移动到下降位置离心瓶", "抽液平台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "下降位置离心瓶"))
							);

						//关闭阀
						await ExecuteSequentialAsync(
							("关闭冷凝管洗液两通阀", "冷凝管洗液两通阀", () => SwitchValveAsync(DOSignalId.CondenserWashLiquidValve, false, 1000))
						);

						////建立真空
						//await ExecuteSequentialAsync(
						//	("建立真空", "冷凝管", () => EstablishVacuumAsync(_condenserPressureSet, 10.0)),
						//	("等待真空建立", "冷凝管", () => WaitForCondenserPressureAsync(_condenserPressureSet, 10, 1800000))
						//);
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 真空建立完成");
					});
						goto case ExperimentSubStage.StartingRotation;

					case ExperimentSubStage.StartingRotation:
						// 配置补液状态
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.StartingRotation,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在配置补液状态");

								if (!_isCurrentMaterialLiquidFinished)
								{
									_refillSituation = 1; // 低液位监测并补液
								}
								else
								{
									if (_isCurrentMaterialLiquidFinished && _isMultiVial && _productCount == 1) //只有打完了，并且有多个原料瓶，并且产物数量只有一个
									{
										_refillSituation = 2; // 物料瓶已打完，需搬运下一瓶
									}
									else
									{
										_refillSituation = 0; // 停止监测补液
									}
								}

								//_refillSituation = 0; // test停止监测补液

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 补液状态设置为 {_refillSituation}");

								// 此处是同步方法，不需要await
								await Task.CompletedTask;
							});
						goto case ExperimentSubStage.MonitoringEvaporation;

					case ExperimentSubStage.MonitoringEvaporation:
						// 2. 开始旋蒸，监控旋蒸过程
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.MonitoringEvaporation,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在开始旋蒸");

								//旋蒸检测开始
								// 创建取消令牌源，用于取消各个监测任务
								using var liquidMonitoringCts = new CancellationTokenSource();
								using var condensateCollectionCts = new CancellationTokenSource();

								// 定义标志位，用于跟踪任务完成状态，避免使用volatile
								bool timeAccumulationFinished = false;
								bool temperatureJudgmentFinished = false;
								bool condensateCollectionInProgress = false;

								// 同步锁对象，用于保护共享变量
								var stateLock = new object();

								// 1. 监测补液任务 - 可取消
								var monitorAndReplenishLiquidTask = Task.Run(async () =>
								{
									try
									{
										_logger.LogInformation("开始监测旋蒸液位");
										var result = await MonitorAndReplenishLiquidAsync(10000, 5000, liquidMonitoringCts.Token);
										_logger.LogInformation($"液位监测任务结束：{result.Message}");
										return result;
									}
									catch (OperationCanceledException)
									{
										_logger.LogInformation("液位监测任务被取消");
										return OperationResult.Ok("液位监测任务被取消");
									}
									catch (Exception ex)
									{
										_logger.LogError(ex, "液位监测任务发生异常");
										throw;
									}
								});

								// 2. 监测旋蒸时间任务
								var accumulateEvaporationTimeTask = Task.Run(async () =>
								{
									try
									{
										_logger.LogInformation("开始监测旋蒸时间");
										var result = await AccumulateRotaryEvaporationTimeAsync(
											experiment,
											(int)_evaporationTime ,//* 60000,
											10000
										);

										// 标记任务完成
										lock (stateLock)
										{
											timeAccumulationFinished = true;
										}

										_logger.LogInformation($"旋蒸时间监测任务结束：{result.Message}");
										return result;
									}
									catch (Exception ex)
									{
										_logger.LogError(ex, "旋蒸时间监测任务发生异常");
										throw;
									}
								});

								// 3. 智能控温任务
								var smartTemperatureJudgmentTask = Task.Run(async () =>
								{
									try
									{
										_logger.LogInformation("开始智能温度判别");
										var result = await SmartTemperatureJudgmentAsync(
											experiment,
											60,
											10000,
											_isSmartTemperatureControl
										);

										// 标记任务完成
										lock (stateLock)
										{
											temperatureJudgmentFinished = true;
										}

										_logger.LogInformation($"智能温度判别任务结束：{result.Message}");
										return result;
									}
									catch (Exception ex)
									{
										_logger.LogError(ex, "智能温度判别任务发生异常");
										throw;
									}
								});

								// 4. 监测冷凝液收集任务 - 可取消，但需要等到收集动作完成
								var monitorCondensateCollectionTask = Task.Run(async () =>
								{
									try
									{
										_logger.LogInformation("开始监测冷凝液收集");
										var result = await MonitorAndCollectCondensateAsync(
											collectionInterval: 10000,
											monitorDuration: 180,
											(inProgress) =>
											{
												// 使用lock保护共享变量访问
												lock (stateLock)
												{
													condensateCollectionInProgress = inProgress;
												}
											},
											condensateCollectionCts.Token
										);
										_logger.LogInformation($"冷凝液收集监测任务结束：{result.Message}");
										return result;
									}
									catch (OperationCanceledException)
									{
										_logger.LogInformation("冷凝液收集监测任务被取消");
										return OperationResult.Ok("冷凝液收集监测任务被取消");
									}
									catch (Exception ex)
									{
										_logger.LogError(ex, "冷凝液收集监测任务发生异常");
										throw;
									}
								});

								// 等待并持续检查完成条件
								_logger.LogInformation("开始检查和等待任务完成");

								bool experimentComplete = false;

								// 检查完成条件的循环
								while (!experimentComplete)
								{
									bool bothComplete = false;
									bool canCancelCondensate = false;

									// 检查时间积累和温度判断是否都已完成
									lock (stateLock)
									{
										bothComplete = timeAccumulationFinished && temperatureJudgmentFinished;
										canCancelCondensate = !condensateCollectionInProgress;
									}

									// 如果时间积累和温度判断都已完成，取消液位监测和可能的冷凝液收集
									if (bothComplete && !experimentComplete)
									{
										experimentComplete = true;
										_logger.LogInformation("旋蒸时间和温度判断都已完成，正在结束监测任务");

										// 取消液位监测
										_logger.LogInformation("取消液位监测任务");
										liquidMonitoringCts.Cancel();
										CancelLiquidMonitoring("旋蒸已完成，取消液位监测任务");

										// 如果冷凝液收集未在进行中，也取消冷凝液收集任务
										if (canCancelCondensate)
										{
											_logger.LogInformation("冷凝液收集未在进行中，取消冷凝液收集任务");
											condensateCollectionCts.Cancel();
										}
										else
										{
											_logger.LogInformation("冷凝液收集正在进行中，等待收集完成");
										}
									}

									// 检查所有任务是否已经完成
									bool allTasksCompleted =
										monitorAndReplenishLiquidTask.IsCompleted &&
										accumulateEvaporationTimeTask.IsCompleted &&
										smartTemperatureJudgmentTask.IsCompleted &&
										monitorCondensateCollectionTask.IsCompleted;

									if (allTasksCompleted)
									{
										_logger.LogInformation("所有监测任务已完成");
										break;
									}

									// 等待一小段时间再检查
									await Task.Delay(2000);
								}

								// 确保等待所有任务完成，即使已经取消
								_logger.LogInformation("等待所有监测任务结束");
								await Task.WhenAll(
									monitorAndReplenishLiquidTask,
									accumulateEvaporationTimeTask,
									smartTemperatureJudgmentTask,
									monitorCondensateCollectionTask
								);

								_logger.LogInformation("所有旋蒸监测任务已完成");
							}
						);
						goto case ExperimentSubStage.FinalCollection;

					case ExperimentSubStage.FinalCollection:
						// 2.5 最终收集
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.FinalCollection,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始执行最终收集");

								// 执行冷凝液收集操作, 破真空
								var isCollectToVial = _isCondensateLiquidCollected || _isCondensateLiquidSampled;
								await ExecuteSequentialAsync(
									("执行冷凝液收集操作", "冷凝管", () => ProcessCondensateLiquidAsync(isCollectToVial))//,
																											 //("执行破真空操作", "冷凝管", () => BreakVacuumAsync())
								);
							});
						goto case ExperimentSubStage.ReturningCollectionBottle;

					case ExperimentSubStage.ReturningCollectionBottle:
						// 3. 归还收集瓶
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.ReturningCollectionBottle,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 判断是否需要归还收集瓶");

								//上升收集插针(如果有瓶子的话)
								if (_isCollectLiquidOccupy)
								{
									await ExecuteSequentialAsync(
										("移动到上升位置", "抽液平台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "上升位置"))
									);

									//定义机器人任务 - 从货架取空离心瓶到收集位

									//搬运空离心瓶至收集位
									await ReturnVialToShelfAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_Empty, (ushort)_condenserLiquidCollectionPosition, 2, true);
									_logger.LogInformation($"实验 {experiment.ExperimentId}: 收集瓶归还完成");
								}
								else
								{
									_logger.LogInformation($"实验 {experiment.ExperimentId}: 没有收集瓶，不需要归还");
								}
							});
						goto case ExperimentSubStage.CollectionInfoJudgment;

					case ExperimentSubStage.CollectionInfoJudgment:
						// 4. 收集信息判断
						bool isContinue = false;
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.CollectionInfoJudgment,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 进行收集信息判断");


								if (_currentProductIndex < _productCount - 1)
								{
									_currentProductIndex++;
									UpdateProductCurrentParameters(experiment);
									_logger.LogInformation($"实验 {experiment.ExperimentId}: 更新产品当前参数, 重新准备环境并进入下一个冷凝过程");
								}
								else
								{
									//关闭TCU、油浴锅,停止旋转电机、破真空
									//var tcu = _deviceManager.GetTCU("TCU_502_1");
									var oilBath = _deviceManager.GetOilBath("OilBath_503_1");
									await ExecuteSequentialAsync(
										//("关闭TCU", "冷凝器", () => tcu.PowerSwitchAsync(false)),
										("关闭加热", "油浴锅", () => oilBath.SetRunningStatusAsync(2)),
										("停止旋转", "旋蒸旋转电机", () => _motorControlService.StopMotorAsync("RotovapRotaryMotor"))//,
																														   //("破真空", "冷凝管", () => BreakVacuumAsync())
									);

									_logger.LogInformation($"实验 {experiment.ExperimentId}: 没有更多冷凝参数，旋蒸阶段完成");
									// 继续执行后续流程，进入Completed子步骤
									isContinue = false;
								}
							});

						if (isContinue)
						{
							goto case ExperimentSubStage.PreparingNewEnvironment;
						}
						else
						{
							goto case ExperimentSubStage.Completed;
						}
					case ExperimentSubStage.PreparingNewEnvironment:
						// 5. 准备新环境  油浴温度，冷凝温度，旋蒸转速
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.PreparingNewEnvironment,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始准备新的旋蒸环境");

								// 设置油浴温度,TCU温度
								var oilBath = _deviceManager.GetOilBath("OilBath_503_1");
								var tcu = _deviceManager.GetTCU("TCU_502_1");
								await ExecuteSequentialAsync(
									("设定温度", "油浴锅", () => oilBath.SetTemperatureAsync(_oilBathTemperature)),
									("设定温度", "冷凝器", () => tcu.SetTemperatureAsync(_condenserTemperature)),
									("旋蒸瓶旋转", "旋蒸旋转电机", () => _motorControlService.JogPlusAsync("RotovapRotaryMotor", _rotarySpeed))
								);

								//等待油浴温度，TCU温度
								await ExecuteParallelAsync(
									("等待油浴锅温度", "油浴锅", () => WaitForOilBathTemperatureAsync("OilBath_503_1", _oilBathTemperature, 1.0, 1800000)),
									("等待TCU温度", "冷凝器", () => WaitForTCUTemperatureAsync("TCU_502_1", _condenserTemperature, 1.0, 1800000))
								);

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 新环境准备完成，准备进入新的旋蒸过程");
							});

						goto case ExperimentSubStage.VacuumBuilding;

					case ExperimentSubStage.Completed:
						// 旋蒸阶段完成
						experiment.CurrentSubStage = ExperimentSubStage.Completed;
						_logger.LogInformation($"实验 {experiment.ExperimentId} 的旋蒸阶段已完成");
						break;

					default:
						_logger.LogWarning($"未知的子阶段: {experiment.CurrentSubStage}，将从头开始执行旋蒸阶段");
						experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
						goto case ExperimentSubStage.NotStarted;
				}

				return new OperationResult { Success = true, Message = "旋蒸阶段完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行实验 {experiment.ExperimentId} 的旋蒸阶段时发生未处理的错误");
				return await HandleExperimentErrorAsync(experiment, ex.Message);
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		/// <summary>
		/// 执行旋蒸残液处理阶段
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteEvaporationResidueProcessingAsync(Experiment experiment)
		{
			_logger.LogInformation($"开始执行实验 {experiment.ExperimentId} 的旋蒸残液处理阶段");

			// 更新实验阶段
			experiment.CurrentStage = ExperimentStage.EvaporationResidueProcessing;

			// 只有在子阶段为NotStarted或为null时才初始化状态变量
			if (experiment.CurrentSubStage == ExperimentSubStage.NotStarted || experiment.CurrentSubStage == null)
			{
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
			}

			// 触发阶段变更事件
			OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.EvaporationResidueProcessing);
			OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.EvaporationResidueProcessing, experiment.CurrentSubStage);

			try
			{
				_currentExperimentId = experiment.ExperimentId;
				_currentStage = ExperimentStage.EvaporationResidueProcessing;
				_currentSubStage = experiment.CurrentSubStage;

				// 根据当前子阶段确定从哪里开始执行
				switch (experiment.CurrentSubStage)
				{
					case ExperimentSubStage.NotStarted:
						// 初始状态，准备开始旋蒸残液处理
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始旋蒸残液处理阶段");
						experiment.CurrentSubStage = ExperimentSubStage.TransportingFlaskToWorkstation;
						goto case ExperimentSubStage.TransportingFlaskToWorkstation;

					case ExperimentSubStage.TransportingFlaskToWorkstation:
						var goCaseSituation = 0;
						// 1. 搬运旋蒸瓶至工作台
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.TransportingFlaskToWorkstation,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在搬运旋蒸瓶至工作台");

								if (!_isEvaporationResidueSampled && !_isEvaporationResidueCollected) //直接回货架
								{
									goCaseSituation = 1;
								}
								else
								{
									if (_isEvaporationResidueSampled) //取样
									{
										goCaseSituation = 2;
									}
									else //收集
									{
										goCaseSituation = 3;
									}
								}

								if (goCaseSituation != 1)
								{

									//定义机器人任务 - 从旋蒸工作台搬运至抽液工作台
									await DismountEvaporationFlaskAsync(_rotaryBottleType, 5, 3);

									_logger.LogInformation($"实验 {experiment.ExperimentId}: 搬运旋蒸瓶至工作台完成");
								}
							});

						if (goCaseSituation == 1)
						{
							goto case ExperimentSubStage.ReturningFlaskToShelf;
						}
						else if (goCaseSituation == 2)
						{
							goto case ExperimentSubStage.SamplingResidues;
						}
						else if (goCaseSituation == 3)
						{
							goto case ExperimentSubStage.CollectingResidues;
						}
						else
						{
							goto case ExperimentSubStage.ReturningFlaskToShelf;
						}


					case ExperimentSubStage.SamplingResidues:
						// 2. 旋蒸残液取样
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.SamplingResidues,
							async () =>
							{
								//找到空的取样瓶
								var emptySamplingLocations = await _storageService.GetBottleLocationsByReservedStatusAsync(ItemType.SampleBottle_8ml, 1);
								//获取空离心瓶位置
								var emptySamplingLocation = emptySamplingLocations.FirstOrDefault();
								_sampleEmptyBottlePosition = emptySamplingLocation.Position;
								//将瓶子状态跟新
								emptySamplingLocation.UpdateIsReserved(2);
								await _storageService.UpdateShelfLocationAsync(emptySamplingLocation);
								//定义机器人任务 - 从货架取空离心瓶到收集位

								//搬运空离心瓶至收集位
								var transportResult = await TransportVialToWorkstationAsync(ItemType.SampleBottle_8ml, FunctionType.Sample_Empty, (ushort)_sampleEmptyBottlePosition, 4, false);




								_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸残液取样完成");
							});
						goto case ExperimentSubStage.CollectingResidues;

					case ExperimentSubStage.CollectingResidues:
						// 3. 旋蒸残液收集
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.CollectingResidues,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在进行旋蒸残液收集");

								// TODO: 实现旋蒸残液收集的具体逻辑
								// 例如：搬运收集瓶、打开收集阀、收集完成后关闭阀门等

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸残液收集完成");
							});
						goto case ExperimentSubStage.ReturningFlaskToShelf;

					case ExperimentSubStage.ReturningFlaskToShelf:
						// 4. 搬回旋蒸瓶至货架
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.ReturningFlaskToShelf,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在搬回旋蒸瓶至货架");


								//_rotaryEmptyBottlePosition

								//定义机器人任务 - 从旋蒸工作台搬运至抽液工作台
								await DismountEvaporationFlaskAsync(_rotaryBottleType, 5, (ushort)_rotaryEmptyBottlePosition);

								////找到空的取样瓶
								//var emptySamplingLocations = await _storageService.GetBottleLocationsByReservedStatusAsync(ItemType.SampleBottle_8ml, 1);
								////获取空离心瓶位置
								//var emptySamplingLocation = emptySamplingLocations.FirstOrDefault();
								//_sampleEmptyBottlePosition = emptySamplingLocation.Position;
								////将瓶子状态跟新
								//emptySamplingLocation.UpdateIsReserved(2);
								//await _storageService.UpdateShelfLocationAsync(emptySamplingLocation);
								////定义机器人任务 - 从货架取空离心瓶到收集位

								////搬运空离心瓶至收集位
								//var transportResult = await TransportVialToWorkstationAsync(ItemType.SampleBottle_8ml, FunctionType.Sample_Empty, (ushort)_sampleEmptyBottlePosition, 4, false);


								_logger.LogInformation($"实验 {experiment.ExperimentId}: 搬回旋蒸瓶至货架完成");
							});
						goto case ExperimentSubStage.Completed;

					case ExperimentSubStage.Completed:
						// 旋蒸残液处理阶段完成
						experiment.CurrentSubStage = ExperimentSubStage.Completed;
						_logger.LogInformation($"实验 {experiment.ExperimentId} 的旋蒸残液处理阶段已完成");
						break;

					default:
						_logger.LogWarning($"未知的子阶段: {experiment.CurrentSubStage}，将从头开始执行旋蒸残液处理阶段");
						experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
						goto case ExperimentSubStage.NotStarted;
				}

				return new OperationResult { Success = true, Message = "旋蒸残液处理阶段完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行实验 {experiment.ExperimentId} 的旋蒸残液处理阶段时发生未处理的错误");
				return await HandleExperimentErrorAsync(experiment, ex.Message);
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		/// <summary>
		/// 执行冷凝液处理阶段
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteCondensateProcessingAsync(Experiment experiment)
		{
			_logger.LogInformation($"开始执行实验 {experiment.ExperimentId} 的冷凝液处理阶段");

			// 更新实验阶段
			experiment.CurrentStage = ExperimentStage.CondensateProcessing;

			// 只有在子阶段为NotStarted或为null时才初始化状态变量
			if (experiment.CurrentSubStage == ExperimentSubStage.NotStarted || experiment.CurrentSubStage == null)
			{
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
			}

			// 触发阶段变更事件
			OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.CondensateProcessing);
			OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.CondensateProcessing, experiment.CurrentSubStage);

			try
			{
				_currentExperimentId = experiment.ExperimentId;
				_currentStage = ExperimentStage.CondensateProcessing;
				_currentSubStage = experiment.CurrentSubStage;

				// 根据当前子阶段确定从哪里开始执行
				switch (experiment.CurrentSubStage)
				{
					case ExperimentSubStage.NotStarted:
						// 初始状态，准备开始冷凝液处理
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始冷凝液处理阶段");
						experiment.CurrentSubStage = ExperimentSubStage.SamplingCondensate;
						goto case ExperimentSubStage.SamplingCondensate;

					case ExperimentSubStage.SamplingCondensate:
						// 1. 采集冷凝液样品
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.SamplingCondensate,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在采集冷凝液样品");

								// TODO: 实现冷凝液取样的具体逻辑
								// 例如：搬运取样瓶、取样完成后归位等

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 冷凝液样品采集完成");
							});
						goto case ExperimentSubStage.Completed;

					case ExperimentSubStage.Completed:
						// 冷凝液处理阶段完成
						experiment.CurrentSubStage = ExperimentSubStage.Completed;
						_logger.LogInformation($"实验 {experiment.ExperimentId} 的冷凝液处理阶段已完成");
						break;

					default:
						_logger.LogWarning($"未知的子阶段: {experiment.CurrentSubStage}，将从头开始执行冷凝液处理阶段");
						experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
						goto case ExperimentSubStage.NotStarted;
				}

				return new OperationResult { Success = true, Message = "冷凝液处理阶段完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行实验 {experiment.ExperimentId} 的冷凝液处理阶段时发生未处理的错误");
				return await HandleExperimentErrorAsync(experiment, ex.Message);
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		/// <summary>
		/// 执行清洗阶段
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecuteCleaningAsync(Experiment experiment)
		{
			_logger.LogInformation($"开始执行实验 {experiment.ExperimentId} 的清洗阶段");

			// 更新实验阶段
			experiment.CurrentStage = ExperimentStage.Cleaning;

			// 只有在子阶段为NotStarted或为null时才初始化状态变量
			if (experiment.CurrentSubStage == ExperimentSubStage.NotStarted || experiment.CurrentSubStage == null)
			{
				experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
			}

			// 触发阶段变更事件
			OnExperimentStageChanged(experiment.ExperimentId, ExperimentStage.Cleaning);
			OnExperimentSubStageChanged(experiment.ExperimentId, ExperimentStage.Cleaning, experiment.CurrentSubStage);

			try
			{
				_currentExperimentId = experiment.ExperimentId;
				_currentStage = ExperimentStage.Cleaning;
				_currentSubStage = experiment.CurrentSubStage;

				// 根据当前子阶段确定从哪里开始执行
				switch (experiment.CurrentSubStage)
				{
					case ExperimentSubStage.NotStarted:
						// 初始状态，准备开始清洗
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始清洗阶段");
						experiment.CurrentSubStage = ExperimentSubStage.CleaningCondenser;
						goto case ExperimentSubStage.CleaningCondenser;

					case ExperimentSubStage.CleaningCondenser:
						// 1. 冷凝管路清洗
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.CleaningCondenser,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在进行冷凝管路清洗");

								// TODO: 实现冷凝管路清洗的具体逻辑
								// 例如：循环清洗液、排放清洗液等操作

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 冷凝管路清洗完成");
							});
						goto case ExperimentSubStage.CleaningRotovapTubes;

					case ExperimentSubStage.CleaningRotovapTubes:
						// 2. 旋蒸管路清洗
						await ExecuteSubStageAsync(
							experiment,
							ExperimentSubStage.CleaningRotovapTubes,
							async () =>
							{
								_logger.LogInformation($"实验 {experiment.ExperimentId}: 正在进行旋蒸管路清洗");

								// TODO: 实现旋蒸管路清洗的具体逻辑
								// 例如：循环清洗液、排放清洗液等操作

								_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸管路清洗完成");
							});
						goto case ExperimentSubStage.Completed;

					case ExperimentSubStage.Completed:
						// 清洗阶段完成
						experiment.CurrentSubStage = ExperimentSubStage.Completed;
						_logger.LogInformation($"实验 {experiment.ExperimentId} 的清洗阶段已完成");
						break;

					default:
						_logger.LogWarning($"未知的子阶段: {experiment.CurrentSubStage}，将从头开始执行清洗阶段");
						experiment.CurrentSubStage = ExperimentSubStage.NotStarted;
						goto case ExperimentSubStage.NotStarted;
				}

				return new OperationResult { Success = true, Message = "清洗阶段完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行实验 {experiment.ExperimentId} 的清洗阶段时发生未处理的错误");
				return await HandleExperimentErrorAsync(experiment, ex.Message);
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		#endregion

		#region IDisposable Implementation

		private bool _disposed = false;

		/// <summary>
		/// 释放资源
		/// </summary>
		/// <param name="disposing">是否释放托管资源</param>
		protected virtual void Dispose(bool disposing)
		{
			if (!_disposed)
			{
				if (disposing)
				{
					// 释放托管资源
					_deviceStatusService.DeviceStatusChanged -= OnDeviceStatusChanged;

					// 取消并释放调压任务
					if (_pressureControlCts != null)
					{
						try
						{
							_pressureControlCts.Cancel();
							_pressureControlCts.Dispose();
							_pressureControlCts = null;
						}
						catch
						{
							// 忽略释放时的异常
						}
					}
				}

				_disposed = true;
			}
		}

		/// <summary>
		/// 释放资源
		/// </summary>
		public void Dispose()
		{
			Dispose(true);
			GC.SuppressFinalize(this);
		}

		/// <summary>
		/// 析构函数
		/// </summary>
		~ExperimentProcessDomainService()
		{
			Dispose(false);
		}

		#endregion


		#region 并行&串行操作

		/// <summary>
		/// 处理并行操作结果，同时执行多个操作并统一处理结果
		/// </summary>
		/// <param name="operations">操作列表，每项包含操作名称、设备名称和操作任务</param>
		/// <param name="failFast">是否在首个操作失败时立即返回</param>
		/// <param name="defaultAlarmType">默认报警类型</param>
		/// <param name="defaultSeverity">默认报警严重程度</param>
		/// <returns>操作结果，失败时抛出异常</returns>
		private async Task<OperationResult> HandleParallelOperationsAsync(
			List<(string OperationName, string DeviceName, Task<OperationResult> Operation,
				  AlarmType AlarmType, AlarmSeverity Severity)> operations,
			bool failFast = true,
			AlarmType defaultAlarmType = AlarmType.ActionFailure,
			AlarmSeverity defaultSeverity = AlarmSeverity.Medium)
		{
			// 创建取消令牌源，用于在任务失败时取消其他任务
			using var cts = new CancellationTokenSource();

			// 同时启动所有操作
			var tasks = operations.Select(o => o.Operation).ToList();
			List<string> errorMessages = new();
			bool allSucceeded = true;

			// 等待所有操作完成
			while (tasks.Any())
			{
				var completedTask = await Task.WhenAny(tasks);
				var index = tasks.IndexOf(completedTask);
				var (operationName, deviceName, _, alarmType, severity) = operations[index];
				var result = await completedTask;

				// 移除已完成的任务
				tasks.RemoveAt(index);

				// 处理失败结果
				if (!result.Success)
				{
					string message = $"{deviceName}执行{operationName}失败: {result.Message}";
					_logger.LogWarning(message);

					try
					{
						// 先执行暂停操作
						_logger.LogWarning($"操作失败，触发暂停操作");
						var pauseResult = await ExecutePauseAsync();
						if (pauseResult.Success)
						{
							_logger.LogInformation("暂停操作执行成功");
						}
						else
						{
							_logger.LogWarning($"暂停操作执行失败: {pauseResult.Message}");
						}
					}
					catch (Exception ex)
					{
						_logger.LogError(ex, $"执行暂停操作时发生错误: {ex.Message}");
					}

					// 然后记录报警
					await _dataRecordingService.RecordAlarmAsync(
						alarmType,
						message,
						severity);

					errorMessages.Add(message);
					allSucceeded = false;

					// 如果设置了快速失败，在首个失败时请求取消所有其他任务并立即返回
					if (failFast)
					{
						cts.Cancel(); // 请求取消其他任务，虽然目前可能没有效果
						throw new OperationFailedException(message, result);
					}
				}
			}

			if (allSucceeded)
			{
				return OperationResult.Ok("所有操作成功完成");
			}
			else
			{
				string combinedMessage = $"部分操作失败：{string.Join("; ", errorMessages)}";
				throw new OperationFailedException(combinedMessage,
					OperationResult.Fail(combinedMessage));
			}
		}


		/// <summary>
		/// 简化版本的并行操作处理方法（工厂模式）
		/// </summary>
		/// <param name="operations">操作元组列表，每个元组包含操作名称、设备名称和操作工厂方法</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> ExecuteParallelAsync(params (string OperationName, string DeviceName, Func<Task<OperationResult>> OperationFactory)[] operations)
		{
			// 创建并执行任务
			var tasks = operations.Select(o =>
				(o.OperationName, o.DeviceName, Operation: o.OperationFactory())).ToArray();

			// 转换为完整参数列表
			var fullOperations = tasks.Select(o =>
				(o.OperationName, o.DeviceName, o.Operation, AlarmType.ActionFailure, AlarmSeverity.Medium)).ToList();

			return await HandleParallelOperationsAsync(fullOperations);
		}


		/// <summary>
		/// 串行执行多个操作，并在第一个失败时抛出异常 (改进版本，使用任务工厂)
		/// </summary>
		/// <param name="operations">操作元组列表，每个元组包含操作名称、设备名称和操作任务工厂</param>
		/// <param name="alarmType">报警类型，默认为操作失败</param>
		/// <param name="severity">报警严重程度，默认为中等</param>
		/// <returns>操作结果，失败时抛出异常</returns>
		private async Task<OperationResult> ExecuteSequentialAsync(
			params (string OperationName, string DeviceName, Func<Task<OperationResult>> OperationFactory)[] operations)
		{
			return await ExecuteSequentialWithAlarmAsync(operations, AlarmType.ActionFailure, AlarmSeverity.Medium);
		}

		/// <summary>
		/// 串行执行多个操作，并在第一个失败时抛出异常 (带报警参数版本)
		/// </summary>
		/// <param name="operations">操作元组列表，每个元组包含操作名称、设备名称和操作任务工厂</param>
		/// <param name="alarmType">报警类型</param>
		/// <param name="severity">报警严重程度</param>
		/// <returns>操作结果，失败时抛出异常</returns>
		private async Task<OperationResult> ExecuteSequentialWithAlarmAsync(
			(string OperationName, string DeviceName, Func<Task<OperationResult>> OperationFactory)[] operations,
			AlarmType alarmType,
			AlarmSeverity severity)
		{
			foreach (var (operationName, deviceName, operationFactory) in operations)
			{
				Console.WriteLine($"开始执行: {operationName}");
				var result = await operationFactory(); // 在这里才创建并执行任务
				Console.WriteLine($"完成执行: {operationName}, 结果: {result.Success}");

				//try
				//{
				await HandleOperationResultAsync(result, operationName, deviceName, alarmType, severity);
				//}
				//catch (OperationFailedException ex)
				//{
				// 这里不需要重复抛出异常，因为HandleOperationResultAsync已经处理了失败情况
				//return OperationResult.Fail(ex.Message);
				//}
			}

			return OperationResult.Ok("所有操作成功完成");
		}





		/// <summary>
		/// 处理操作结果，如果失败则记录报警并抛出异常
		/// </summary>
		/// <param name="result">操作结果</param>
		/// <param name="operationName">操作名称</param>
		/// <param name="deviceName">设备名称</param>
		/// <param name="alarmType">报警类型，默认为操作失败</param>
		/// <param name="severity">报警严重程度，默认为中等</param>
		/// <returns>操作结果是否成功，失败时抛出异常</returns>
		private async Task<bool> HandleOperationResultAsync(OperationResult result, string operationName, string deviceName,
			AlarmType alarmType = AlarmType.ActionFailure, AlarmSeverity severity = AlarmSeverity.Medium)
		{
			if (!result.Success)
			{
				string message = $"{deviceName}执行{operationName}失败: {result.Message}";
				_logger.LogWarning(message);

				try
				{
					// 先执行暂停操作
					_logger.LogWarning($"操作失败，触发暂停操作");
					var pauseResult = await ExecutePauseAsync();
					if (pauseResult.Success)
					{
						_logger.LogInformation("暂停操作执行成功");
					}
					else
					{
						_logger.LogWarning($"暂停操作执行失败: {pauseResult.Message}");
					}
				}
				catch (Exception ex)
				{
					_logger.LogError(ex, $"执行暂停操作时发生错误: {ex.Message}");
				}

				// 然后记录报警
				await _dataRecordingService.RecordAlarmAsync(
					alarmType,
					message,
					severity);

				// 抛出异常而不是返回false
				throw new OperationFailedException(message, result);
			}
			return true;
		}

		/// <summary>
		/// 支持取消的简化并行操作执行方法
		/// </summary>
		/// <param name="operations">操作数组</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> ExecuteCancellableParallelAsync(params (string OperationName, string DeviceName, Func<Task<OperationResult>> OperationFactory)[] operations)
		{
			// 创建取消令牌源
			using var cts = new CancellationTokenSource();

			try
			{
				// 在原有的任务基础上包装，使其支持取消
				var wrappedTasks = new List<(string OperationName, string DeviceName, Func<Task<OperationResult>> OperationFactory)>();

				foreach (var op in operations)
				{
					// 创建一个包装任务，它会监视取消令牌
					var wrappedFactory = new Func<Task<OperationResult>>(async () =>
					{
						// 创建一个完成源，以便我们可以从外部取消任务
						var tcs = new TaskCompletionSource<OperationResult>();

						// 注册取消令牌的回调
						cts.Token.Register(() =>
						{
							tcs.TrySetCanceled();
						}, useSynchronizationContext: false);

						// 创建一个竞争：原始任务 vs 取消
						var originalTask = op.OperationFactory();
						var completedTask = await Task.WhenAny(originalTask, tcs.Task);

						if (completedTask == tcs.Task)
						{
							// 任务被取消
							_logger.LogInformation($"{op.DeviceName}执行{op.OperationName}操作已取消");
							return OperationResult.Ok($"{op.OperationName}已取消");
						}
						else
						{
							// 原始任务完成
							var result = await originalTask;
							if (!result.Success)
							{
								// 如果任务失败，请求取消所有其他任务
								cts.Cancel();
							}
							return result;
						}
					});

					wrappedTasks.Add((op.OperationName, op.DeviceName, wrappedFactory));
				}

				// 使用普通的ExecuteParallelAsync执行包装后的任务
				return await ExecuteParallelAsync(wrappedTasks.ToArray());
			}
			catch (Exception ex)
			{
				// 确保在异常情况下也能取消所有任务
				cts.Cancel();
				_logger.LogError(ex, "可取消并行任务执行异常");
				return OperationResult.Fail($"并行操作失败: {ex.Message}");
			}
		}
		#endregion



		#region 工艺辅助方法

		/// <summary>
		/// 监测旋蒸液位并自动补液
		/// </summary>
		/// <param name="lowLiquidLevelDelay">低液位信号延时(s)</param>
		/// <param name="monitorInterval">监测间隔(ms)</param>
		/// <param name="cancellationToken">取消令牌</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> MonitorAndReplenishLiquidAsync(
			int lowLiquidLevelDelay,
			int monitorInterval = 10000,
			CancellationToken cancellationToken = default)
		{
			_logger.LogInformation($"开始监测旋蒸液位，低液位信号延时 {lowLiquidLevelDelay}s");
			try
			{
				// 重置取消标记
				_cancelLiquidMonitoring = false;

				// 重置信号等待取消标志
				ResetSpecificSignalWaitCancelFlag(DISignalId.EvaporateFlaskLevelSensor);

				// 补液循环
				while (!cancellationToken.IsCancellationRequested)
				{
					// 检查是否有外部取消请求
					if (_cancelLiquidMonitoring)
					{
						_logger.LogWarning("收到外部取消液位监测请求，终止液位监测循环");
						break;
					}

					// 检查是否需要继续监测
					if (_refillSituation == 0)
					{
						_logger.LogInformation("补液情况设置为0，终止液位监测");
						break;
					}

					// 情况1: 当前瓶子未打完，需要监测低液位并补液
					if (_refillSituation == 1)
					{
						_logger.LogInformation("监测低液位信号，当检测到低液位时将自动补液");

						// 创建取消令牌源，用于等待低液位时可以取消
						using var linkedCts = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);

						try
						{
							// 等待低液位信号，但可以被外部取消
							var waitTask = WaitForSpecificSignalStateAsync(
								DISignalId.EvaporateFlaskLevelSensor,
								false,
								86400000, // 超时1天
								lowLiquidLevelDelay * 1000, // 转换为毫秒
								"外部信号指示液体已打完，终止等待"
							);

							// 添加超时任务，以便可以定期检查取消请求
							var timeoutTask = Task.Delay(Math.Min(30000, monitorInterval), linkedCts.Token);

							// 等待任一任务完成
							await Task.WhenAny(waitTask, timeoutTask);

							// 如果是取消请求，直接中断等待
							if (cancellationToken.IsCancellationRequested || _cancelLiquidMonitoring)
							{
								linkedCts.Cancel(); // 同步取消内部等待
								_logger.LogInformation("收到取消请求，终止液位监测");
								break;
							}

							// 如果信号等待已完成并成功
							if (waitTask.IsCompleted && !timeoutTask.IsCompleted)
							{
								var lowLevelResult = await waitTask;

								// 如果等待被取消或发生错误，可能是外部通知液体已打完
								if (!lowLevelResult.Success || _isCurrentMaterialLiquidFinished)
								{
									_logger.LogInformation("收到液体已打完信号或等待过程中发生错误，终止当前瓶子的补液监测");

									// 检查是否需要搬回物料瓶
									if (_isCurrentMaterialLiquidFinished && _isExtractLiquidOccupy)
									{
										// 执行物料瓶归位操作
										await ReturnCurrentMaterialVialAsync();
									}

									if (_refillSituation == 0)
									{
										break; // 如果补液情况为0，跳出监测循环
									}
									continue; // 继续循环，处理其他情况
								}

								// 如果成功等到低液位信号，开始补液
								_logger.LogWarning("检测到持续低液位信号，开始执行补液操作");

								// 计算补液量，确保不超过剩余量
								double pumpVolume = Math.Min(100, _unPumpedLiquidVolume); // 每次最多补100ml

								// 调用旋蒸阶段补液方法
								var pumpResult = await ReplenishLiquidForRotaryEvaporationAsync(pumpVolume);

								// 如果补液失败，记录错误但继续监测
								if (!pumpResult.Success)
								{
									_logger.LogError($"补液操作失败: {pumpResult.Message}");
								}
								else
								{
									_logger.LogInformation($"补液操作完成，已补充{pumpVolume}ml，继续监测液位");

									// 更新未打完液体量
									_unPumpedLiquidVolume -= pumpVolume;

									// 检查是否已经打完
									if (_unPumpedLiquidVolume <= 0)
									{
										_isCurrentMaterialLiquidFinished = true;
										_logger.LogInformation("当前物料瓶液体已打完");

										// 执行物料瓶归位操作
										await ReturnCurrentMaterialVialAsync();

										if (_refillSituation == 0)
										{
											break; // 如果补液情况为0，跳出监测循环
										}
									}
								}
							}
						}
						catch (OperationCanceledException)
						{
							// 正常取消处理
							_logger.LogInformation("液位监测等待操作被取消");
							if (cancellationToken.IsCancellationRequested)
							{
								// 外部取消请求，终止整个循环
								break;
							}
						}
					}
					// 情况2: 当前瓶子已打完，需要搬运下一个瓶子
					else if (_refillSituation == 2)
					{
						_logger.LogInformation("当前物料瓶已打完，准备搬运下一个原料瓶");

						// 检查是否还有可用的物料瓶
						if (_currentVialIndex >= _materialVialPositions.Count)
						{
							_logger.LogWarning("没有更多的原料瓶可用，终止补液");
							_refillSituation = 0;
							break;
						}

						// 检查是否有外部取消请求
						if (cancellationToken.IsCancellationRequested)
						{
							_logger.LogInformation("收到取消请求，终止搬运下一个物料瓶操作");
							break;
						}

						// 获取下一个物料瓶位置
						_materialCentrifugePosition = _materialVialPositions[_currentVialIndex];

						// 获取瓶子信息并更新状态
						try
						{
							var materialVialLocation = await _storageService.GetShelfLocationAsync(LocationCode.Shelf, _materialCentrifugePosition);
							materialVialLocation.UpdateIsReserved(2);
							await _storageService.UpdateShelfLocationAsync(materialVialLocation);

							// 构建机器人搬运任务

							// 执行搬运
							var transportResult = await TransportVialToWorkstationAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_To_Rotovap, (ushort)_materialCentrifugePosition, 3, true);
							if (!transportResult.Success)
							{
								_logger.LogError($"搬运下一个物料瓶失败: {transportResult.Message}");
								_refillSituation = 0; // 搬运失败，终止补液
								break;
							}

							// 重置物料状态
							_isCurrentMaterialLiquidFinished = false;
							_isExtractLiquidOccupy = true;
							_unPumpedLiquidVolume = _centrifugeBottleVolume; // 假设新瓶子是满的
							_refillSituation = 1; // 切换回监测模式

							_logger.LogInformation($"成功搬运下一个物料瓶(位置:{_materialCentrifugePosition})至工作台，切换为液位监测模式");
						}
						catch (Exception ex)
						{
							_logger.LogError(ex, "搬运下一个物料瓶过程中发生错误");
							_refillSituation = 0; // 出错，终止补液
							break;
						}
					}

					// 为防止循环过快，添加短暂延时，同时检查取消请求
					try
					{
						await Task.Delay(monitorInterval, cancellationToken);
					}
					catch (OperationCanceledException)
					{
						// 取消延时，终止循环
						_logger.LogInformation("液位监测延时被取消，终止液位监测循环");
						break;
					}
				}

				if (cancellationToken.IsCancellationRequested)
				{
					_logger.LogInformation("液位监测任务因取消令牌被取消");
					return OperationResult.Ok("液位监测被取消");
				}
				else
				{
					_logger.LogInformation("液位监测循环正常结束");
					return OperationResult.Ok("液位监测完成");
				}
			}
			catch (OperationCanceledException)
			{
				_logger.LogInformation("液位监测任务被取消");
				return OperationResult.Ok("液位监测被取消");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"监测旋蒸液位过程中发生异常");
				return OperationResult.Fail($"监测旋蒸液位过程中发生异常: {ex.Message}");
			}
			finally
			{
				// 取消液位监测
				CancelLiquidMonitoring("任务结束或被取消");

				// 确保重置取消标志
				ResetSpecificSignalWaitCancelFlag(DISignalId.EvaporateFlaskLevelSensor);
				// 重置取消标记
				_cancelLiquidMonitoring = false;
			}
		}

		/// <summary>
		/// 将当前物料瓶从抽液位归还到货架
		/// </summary>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> ReturnCurrentMaterialVialAsync()
		{
			try
			{
				_logger.LogInformation($"开始将物料瓶(位置:{_materialCentrifugePosition})从工作台抽液位搬回货架");

				// 执行搬运回货架
				var returnResult = await ReturnVialToShelfAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_To_Rotovap, 1, (ushort)_materialCentrifugePosition, true);
				if (!returnResult.Success)
				{
					_logger.LogWarning($"物料瓶搬回失败: {returnResult.Message}");
					return returnResult;
				}

				// 更新物料瓶状态
				_isExtractLiquidOccupy = false;

				if (_isMultiVial)
				{
					_currentVialIndex++; //当前物料瓶索引加1
				}

				_logger.LogInformation($"成功将物料瓶从工作台抽液位搬回货架位置{_materialCentrifugePosition}");

				// 根据不同情况设置补液状态
				if (_isMultiVial && _currentVialIndex < _materialVialCount)
				{
					//需要搬运下一瓶
					_refillSituation = 2;
					_logger.LogInformation("准备搬运下一瓶，补液模式设置为2");
				}
				else
				{
					//补液结束
					_refillSituation = 0;
					_logger.LogInformation("补液结束，补液模式设置为0");
				}

				return returnResult;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "归还物料瓶过程中发生错误");
				return OperationResult.Fail($"归还物料瓶过程中发生错误: {ex.Message}");
			}
		}

		/// <summary>
		/// 累计旋蒸时间
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <param name="targetDuration">目标时长(分钟)</param>
		/// <param name="checkInterval">检查间隔(ms)</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> AccumulateRotaryEvaporationTimeAsync(
			Experiment experiment,
			int targetDuration,
			int checkInterval = 10000)
		{
			var startTime = DateTime.Now;
			TimeSpan totalDuration = TimeSpan.Zero;
			TimeSpan pauseDuration = TimeSpan.Zero;
			DateTime? pauseStartTime = null;
			bool isPaused = false;

			_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始累计旋蒸时间，目标时长 {targetDuration} 分钟");

			try
			{
				while (totalDuration.TotalMinutes < targetDuration)
				{
					// 检查实验是否需要暂停
					bool shouldBePaused = experiment.Status == ExperimentStatus.Paused;

					// 处理暂停开始
					if (shouldBePaused && !isPaused)
					{
						isPaused = true;
						pauseStartTime = DateTime.Now;
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸计时暂停，当前已累计 {totalDuration.TotalMinutes:F1} 分钟");
					}
					// 处理暂停结束
					else if (!shouldBePaused && isPaused)
					{
						isPaused = false;
						if (pauseStartTime.HasValue)
						{
							pauseDuration += DateTime.Now - pauseStartTime.Value;
							pauseStartTime = null;
							_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸计时继续，当前已累计 {totalDuration.TotalMinutes:F1} 分钟");
						}
					}

					// 计算当前累计时间
					if (!isPaused)
					{
						totalDuration = DateTime.Now - startTime - pauseDuration;

						// 记录累计时间
						if (totalDuration.TotalMinutes % 0.5 < 0.1) // 每5分钟记录一次
						{
							_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸已进行 {totalDuration.TotalMinutes:F1} 分钟，目标 {targetDuration} 分钟");
						}
					}

					await Task.Delay(checkInterval);
				}

				_logger.LogInformation($"实验 {experiment.ExperimentId}: 旋蒸时间累计完成，共 {totalDuration.TotalMinutes:F1} 分钟");
				return OperationResult.Ok($"旋蒸时间累计完成: {totalDuration.TotalMinutes:F1}分钟");
			}
			catch (Exception ex)
			{
				string errorMessage = $"累计旋蒸时间过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);
				return OperationResult.Fail(errorMessage);
			}
		}

		/// <summary>
		/// 智能温度判别
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <param name="monitorDuration">监测持续时间(分钟)</param>
		/// <param name="checkInterval">检查间隔(ms)</param>
		/// <param name="enableSmartTemperatureJudgment">是否启用智能温度判别</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> SmartTemperatureJudgmentAsync(
			Experiment experiment,
			int monitorDuration = 60,
			int checkInterval = 10000,
			bool enableSmartTemperatureJudgment = false)
		{
			try
			{
				// 如果不启用智能温度判别，直接返回成功
				if (!enableSmartTemperatureJudgment)
				{
					_logger.LogInformation($"实验 {experiment.ExperimentId}: 未启用智能温度判别，跳过判别过程");
					return OperationResult.Ok("未启用智能温度判别，跳过判别过程");
				}

				var startTime = DateTime.Now;
				var endTime = startTime.AddMinutes(monitorDuration);

				// 重置温度判别数据
				_temperatureJudgmentData.Reset();

				// 设置判别参数
				_temperatureJudgmentData.StableThreshold = 0.3;
				_temperatureJudgmentData.StableCountRequired = 6;
				_temperatureJudgmentData.StableAfterPeakRequired = 10;

				_logger.LogInformation($"实验 {experiment.ExperimentId}: 开始智能温度判别，监测持续时间 {monitorDuration}分钟");

				while (DateTime.Now < endTime)
				{
					// 获取当前旋蒸出口温度
					double outletTemperature = MainTempCollectorStatus.Temperature1;

					// 获取当前油浴温度（仅用于记录，不参与判断）
					double currentOilBathTemperature = MainOilBathStatus.CurrentTemperaturePV;

					// 更新温度判别数据
					_temperatureJudgmentData.CurrentOilBathTemperature = currentOilBathTemperature;
					_temperatureJudgmentData.AddTemperature(outletTemperature);

					_logger.LogDebug($"实验 {experiment.ExperimentId}: 当前旋蒸出口温度 {outletTemperature:F1}℃, 油浴温度 {currentOilBathTemperature:F1}℃");

					// 检查是否发现温度峰值
					if (_temperatureJudgmentData.CheckPeakDetection())
					{
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 检测到温度峰值 {_temperatureJudgmentData.HighestTemperature:F1}℃，温度开始下降");
					}

					// 检查温度稳定性
					_temperatureJudgmentData.CheckTemperatureStability();

					// 检查是否在最低点稳定
					if (_temperatureJudgmentData.CheckStableLowestPoint())
					{
						double averageTemp = _temperatureJudgmentData.GetRecentTemperatureAverage();
						_logger.LogInformation($"实验 {experiment.ExperimentId}: 确认温度在峰值后的稳定最低点 {averageTemp:F1}℃，较峰值 {_temperatureJudgmentData.HighestTemperature:F1}℃ 下降了 {(_temperatureJudgmentData.HighestTemperature - averageTemp):F1}℃");

						// 设置判别结果
						_temperatureJudgmentData.IsJudgmentCompleted = true;
						_temperatureJudgmentData.JudgmentResult = $"温度从峰值 {_temperatureJudgmentData.HighestTemperature:F1}℃ 下降到稳定最低点 {averageTemp:F1}℃，判断旋蒸已结束";

						return OperationResult.Ok(_temperatureJudgmentData.JudgmentResult);
					}

					// 如果判别过程已结束，提前退出
					if (_temperatureJudgmentData.IsJudgmentCompleted)
					{
						return OperationResult.Ok(_temperatureJudgmentData.JudgmentResult);
					}

					await Task.Delay(checkInterval);
				}

				// 监测时间结束，但未检测到旋蒸结束特征
				_logger.LogWarning($"实验 {experiment.ExperimentId}: 智能温度判别监测时间已到，但未检测到明确的旋蒸结束特征");

				// 设置判别结果
				_temperatureJudgmentData.IsJudgmentCompleted = true;
				_temperatureJudgmentData.JudgmentResult = $"智能温度判别监测时间已到，未检测到明确的旋蒸结束特征。峰值: {_temperatureJudgmentData.HighestTemperature:F1}℃, 峰值后最低: {_temperatureJudgmentData.LowestTemperatureAfterPeak:F1}℃";

				return OperationResult.Ok(_temperatureJudgmentData.JudgmentResult);
			}
			catch (Exception ex)
			{
				string errorMessage = $"智能温度判别过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);

				// 设置判别结果
				_temperatureJudgmentData.IsJudgmentCompleted = true;
				_temperatureJudgmentData.JudgmentResult = errorMessage;

				return OperationResult.Fail(errorMessage);
			}
		}

		/// <summary>
		/// 监测冷凝收集液位并收集
		/// </summary>
		/// <param name="collectionInterval">收集检查间隔(ms)</param>
		/// <param name="monitorDuration">监测持续时间(分钟)</param>
		/// <param name="collectionInProgressCallback">回调函数，通知收集动作进行状态</param>
		/// <param name="cancellationToken">取消令牌</param>
		/// <returns>操作结果</returns>
		private async Task<OperationResult> MonitorAndCollectCondensateAsync(
			int collectionInterval = 30000, // 默认每30秒检查一次
			int monitorDuration = 180, // 默认监测3小时
			Action<bool> collectionInProgressCallback = null, // 回调函数，通知收集动作进行状态
			CancellationToken cancellationToken = default)
		{
			_logger.LogInformation($"开始监测冷凝液收集流程");
			bool condenserLevelReached = false;

			// 重置冷凝液位传感器等待取消标志
			ResetSpecificSignalWaitCancelFlag(DISignalId.CondenserLevelSensor);

			try
			{
				// 定义监测结束时间
				var endTime = DateTime.Now.AddMinutes(monitorDuration);

				// 监测循环
				while (DateTime.Now < endTime && !cancellationToken.IsCancellationRequested)
				{
					// 标记收集动作未进行中
					collectionInProgressCallback?.Invoke(false);

					// 1. 监测冷凝液位传感器，等待冷凝液位到位信号持续一段时间
					_logger.LogInformation("等待冷凝液位传感器信号稳定");

					// 设置等待超时，不超过剩余监测时间
					int timeoutMs = Math.Min((int)(endTime - DateTime.Now).TotalMilliseconds, collectionInterval);
					if (timeoutMs <= 0) break; // 如果时间已经到了，退出循环

					// 等待信号状态持续一段时间
					var condenserLevelResult = await WaitForSpecificSignalStateAsync(
						DISignalId.CondenserLevelSensor,
						true,
						timeoutMs: timeoutMs,
						holdTimeMs: 3000, // 持续3秒判断为稳定
						cancellationReason: "监测时间结束或外部取消"
					);

					// 检查是否需要取消监测
					if (cancellationToken.IsCancellationRequested)
					{
						_logger.LogInformation("收到取消请求，停止冷凝液收集监测");
						break;
					}

					// 如果成功检测到稳定的冷凝液位信号
					if (condenserLevelResult.Success)
					{
						condenserLevelReached = true;

						// 标记收集动作进行中
						collectionInProgressCallback?.Invoke(true);

						// 2. 如果收集液位到位，关闭冷凝开关阀电机
						_logger.LogInformation("检测到冷凝液位到位，关闭冷凝开关阀电机");
						await ExecuteSequentialAsync(
							("关闭冷凝开关阀", "冷凝开关阀电机", () => _motorControlService.MoveToPositionAsync("CondenserValveMotor", "关闭位置"))
						);

						// 3. 根据配置决定冷凝液处理方式
						if (!_isCondensateLiquidCollected && !_isCondensateLiquidSampled)
						{
							// 直接排废
							_logger.LogInformation("冷凝液未设置收集和取样，执行排废流程");
							await ProcessCondensateLiquidAsync(isCollectToVial: false);
						}
						else
						{
							// 排到收集瓶
							_logger.LogInformation("冷凝液设置为收集或取样，执行收集到瓶流程");

							// 检查收集位是否有瓶子
							if (!_isCollectLiquidOccupy)
							{
								_logger.LogInformation("收集位无瓶子，开始搬运空瓶到收集位");

								var emptyCentrifugeLocations = await _storageService.GetBottleLocationsByReservedStatusAsync(ItemType.CentrifugeBottle_500ml, 1);
								//获取空离心瓶位置
								var emptyCentrifugeLocation = emptyCentrifugeLocations.FirstOrDefault();
								_condenserLiquidCollectionPosition = emptyCentrifugeLocation.Position;
								//将瓶子状态跟新
								emptyCentrifugeLocation.UpdateIsReserved(2);
								await _storageService.UpdateShelfLocationAsync(emptyCentrifugeLocation);
								//定义机器人任务 - 从货架取空离心瓶到收集位

								//搬运空离心瓶至收集位
								var transportResult = await TransportVialToWorkstationAsync(ItemType.CentrifugeBottle_500ml, FunctionType.Centrifuge_Empty, (ushort)_condenserLiquidCollectionPosition, 4, true);


								if (!transportResult.Success)
								{
									_logger.LogError($"搬运冷凝液收集瓶失败: {transportResult.Message}");
								}
								else //成功搬运空离心瓶到收集位
								{
									_isCollectLiquidOccupy = true;
									await ProcessCondensateLiquidAsync(isCollectToVial: true);
								}
							}
							else
							{
								_logger.LogInformation("收集位已有瓶子，执行收集流程");
								await ProcessCondensateLiquidAsync(isCollectToVial: true);
							}
						}

						// 标记收集动作已完成
						collectionInProgressCallback?.Invoke(false);
					}

					// 间隔一段时间后继续检查
					if (!cancellationToken.IsCancellationRequested && DateTime.Now < endTime)
					{
						await Task.Delay(Math.Min(collectionInterval, 5000), cancellationToken);
					}
				}

				return OperationResult.Ok("冷凝液监测与收集完成");
			}
			catch (OperationCanceledException)
			{
				// 正常取消，返回成功但带有取消信息
				return OperationResult.Ok("冷凝液监测与收集被取消");
			}
			catch (Exception ex)
			{
				string errorMessage = $"监测冷凝收集液位过程出现异常: {ex.Message}";
				_logger.LogError(ex, errorMessage);
				return OperationResult.Fail(errorMessage);
			}
			finally
			{
				// 确保最终通知收集动作已完成
				collectionInProgressCallback?.Invoke(false);

				// 重置信号等待取消标志
				ResetSpecificSignalWaitCancelFlag(DISignalId.CondenserLevelSensor);

				// 取消对冷凝液位传感器的监测
				CancelSpecificSignalWait(DISignalId.CondenserLevelSensor, "监测任务结束，取消冷凝液位传感器监测");
			}
		}

		/// <summary>
		/// 处理冷凝液（排废或收集到瓶）
		/// </summary>
		/// <param name="isCollectToVial">是否收集到瓶子</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ProcessCondensateLiquidAsync(bool isCollectToVial = false)
		{
			try
			{
				if (isCollectToVial)
				{
					// 收集到瓶子的流程
					_logger.LogInformation("执行冷凝液收集到瓶操作");

					await ExecuteSequentialAsync(
						("移动到下降位置离心瓶", "抽液平台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "下降位置离心瓶"))
					);

					// 并行执行阀门开关操作
					await ExecuteParallelAsync(
						("打开冷凝液回收两通阀", "冷凝液回收两通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleValve, true, 1000)),
						("打开冷凝管液回收三通", "冷凝管液回收三通", () => SwitchValveAsync(DOSignalId.CondensateRecycleThreeWayValve, true, 1000))
					);
				}
				else
				{
					// 直接排废路径
					_logger.LogInformation("执行冷凝液排废操作");
					// 并行执行阀门开关操作
					await ExecuteParallelAsync(
						("打开冷凝液回收两通阀", "冷凝液回收两通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleValve, true, 1000)),
						("关闭冷凝管液回收三通", "冷凝管液回收三通", () => SwitchValveAsync(DOSignalId.CondensateRecycleThreeWayValve, false, 1000))
					);
				}

				// 等待阀门打开
				await Task.Delay(2000);

				// 排放冷凝液
				_logger.LogInformation("打开排冷凝液两通气阀");
				await ExecuteSequentialAsync(
					("打开排冷凝液两通气阀", "排冷凝液两通气阀", () => SwitchValveAsync(DOSignalId.ExhaustCondensateLiquidValve, true, 1000))
				);

				// 等待排液完成
				_logger.LogInformation("等待排液完成，持续 10 秒");
				await Task.Delay(TimeSpan.FromSeconds(20));

				// 关闭排液阀
				_logger.LogInformation("关闭排冷凝液两通气阀");
				await ExecuteSequentialAsync(
					("关闭排冷凝液两通气阀", "排冷凝液两通气阀", () => SwitchValveAsync(DOSignalId.ExhaustCondensateLiquidValve, false, 1000))
				);

				// 顺序关闭其他阀门
				await ExecuteSequentialAsync(
					("关闭冷凝液回收两通阀", "冷凝液回收两通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleValve, false, 1000))//,
																													  //("打开冷凝开关阀", "冷凝开关阀电机", () => _motorControlService.MoveToPositionAsync("CondenserValveMotor", "打开位置"))
				);

				return OperationResult.Ok($"冷凝液已成功{(isCollectToVial ? "收集到瓶" : "排废")}");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "处理冷凝液过程中发生错误");

				return OperationResult.Fail($"处理冷凝液过程中发生错误: {ex.Message}");
			}
		}

		#endregion


		/// <summary>
		/// 执行可暂停的打液操作
		/// </summary>
		/// <param name="motorId">泵电机ID</param>
		/// <param name="volumeML">打液量(ml)</param>
		/// <param name="conversionFactor">转换因子(ml/圈)</param>
		/// <param name="speedRPM">打液速度(RPM)</param>
		/// <param name="monitorLiquidLevel">是否监控液位传感器</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ExecutePausableDispensingAsync(
			string motorId,
			double volumeML,
			double conversionFactor,
			double speedRPM = 60.0,
			bool monitorLiquidLevel = false)
		{
			try
			{
				_logger.LogInformation($"开始执行可暂停的打液操作: 电机={motorId}, 目标体积={volumeML}ml, 是否监控液位={monitorLiquidLevel}");

				// 重置信号等待取消标志
				ResetSpecificSignalWaitCancelFlag(DISignalId.EvaporateFlaskLevelSensor);

				// 启动打液任务
				var dispensingTask = _motorControlService.DispensingLiquidAsync(motorId, volumeML, conversionFactor, speedRPM);

				// 用于存储上次液位状态，避免重复日志
				bool? lastLiquidLevelHigh = null;
				// 记录上次液位检查时间，避免频繁检查
				DateTime lastLiquidLevelCheckTime = DateTime.MinValue;
				// 液位检查的间隔时间(ms)
				const int liquidLevelCheckInterval = 5000;
				// 液位高位保持时间(ms)，必须连续检测到高位达到此时间才会暂停
				const int liquidLevelHighHoldTime = 10000;
				// 液位低位保持时间(ms)，必须连续检测到低位达到此时间才会恢复
				const int liquidLevelLowHoldTime = 10000;

				// 预先启动等待信号的任务，但先不等待它们完成
				Task<OperationResult> highLevelWaitTask = null;
				Task<OperationResult> lowLevelWaitTask = null;

				// 提前启动高位信号等待任务
				_logger.LogDebug("预先启动高位信号等待任务");
				highLevelWaitTask = WaitForSpecificSignalStateAsync(
					DISignalId.PushRodExtendLimitSensor,//EvaporateFlaskLevelSensor,
					false,
					int.MaxValue, // 使用最大超时值，依靠取消机制来终止等待
					liquidLevelHighHoldTime,
					"打液已完成，终止等待");

				// 定期检查打液进度，直到完成
				while (!dispensingTask.IsCompleted)
				{
					// 获取当前已打液量
					double currentVolume = _motorControlService.GetCurrentDispensedVolume();
					double progressPercent = (currentVolume / volumeML) * 100;
					_logger.LogInformation($"当前打液进度: {currentVolume:F2}ml / {volumeML:F2}ml ({progressPercent:F1}%)");

					// 如果需要监控液位传感器，且时间间隔已满足
					if (monitorLiquidLevel && (DateTime.Now - lastLiquidLevelCheckTime).TotalMilliseconds >= liquidLevelCheckInterval)
					{
						lastLiquidLevelCheckTime = DateTime.Now;

						// 获取液位传感器当前状态
						bool currentLiquidLevelHigh = GetDISignalState(DISignalId.EvaporateFlaskLevelSensor);

						// 如果液位状态发生变化，记录日志
						if (lastLiquidLevelHigh != currentLiquidLevelHigh)
						{
							_logger.LogInformation($"液位传感器状态变化: {(currentLiquidLevelHigh ? "高位" : "低位")}");
							lastLiquidLevelHigh = currentLiquidLevelHigh;
						}

						// 检查高位信号等待任务是否完成
						if (highLevelWaitTask != null && highLevelWaitTask.IsCompleted)
						{
							var highLevelResult = await highLevelWaitTask;

							if (highLevelResult.Success && !dispensingTask.IsCompleted)
							{
								// 获取最新的打液量用于记录
								currentVolume = _motorControlService.GetCurrentDispensedVolume();
								progressPercent = (currentVolume / volumeML) * 100;

								_logger.LogWarning($"检测到液位传感器持续高位信号，自动暂停打液，当前已打液: {currentVolume:F2}ml");
								PauseDispensing();

								// 启动低位信号等待任务
								_logger.LogDebug("启动低位信号等待任务");
								lowLevelWaitTask = WaitForSpecificSignalStateAsync(
									DISignalId.PushRodExtendLimitSensor,
									true,
									int.MaxValue, // 使用最大超时值，依靠取消机制来终止等待
									liquidLevelLowHoldTime,
									"打液已完成，终止等待");
							}

							// 无论成功与否，重置高位等待任务为null，表示此次等待已完成
							highLevelWaitTask = null;
						}

						// 检查低位信号等待任务是否完成
						if (lowLevelWaitTask != null && lowLevelWaitTask.IsCompleted)
						{
							var lowLevelResult = await lowLevelWaitTask;

							if (lowLevelResult.Success && !dispensingTask.IsCompleted)
							{
								// 获取最新的打液量用于记录
								currentVolume = _motorControlService.GetCurrentDispensedVolume();
								progressPercent = (currentVolume / volumeML) * 100;

								_logger.LogInformation($"检测到液位传感器持续低位信号，自动恢复打液，当前已打液: {currentVolume:F2}ml");
								ResumeDispensing();

								// 恢复打液后，重新启动高位信号等待任务
								_logger.LogDebug("重新启动高位信号等待任务");
								highLevelWaitTask = WaitForSpecificSignalStateAsync(
									DISignalId.EvaporateFlaskLevelSensor,
									true,
									int.MaxValue, // 使用最大超时值，依靠取消机制来终止等待
									liquidLevelHighHoldTime,
									"打液已完成，终止等待");
							}

							// 无论成功与否，重置低位等待任务为null，表示此次等待已完成
							lowLevelWaitTask = null;
						}
					}


					// 等待一段时间再检查
					await Task.Delay(1000);
				}

				// 确保取消所有可能的等待操作
				CancelSpecificSignalWait(DISignalId.EvaporateFlaskLevelSensor, "打液已完成，终止所有等待");

				// 获取打液结果
				var result = await dispensingTask;

				// 返回打液结果
				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"执行可暂停打液操作时发生异常");
				return OperationResult.Fail($"执行可暂停打液操作时发生异常: {ex.Message}");
			}
			finally
			{
				// 确保重置取消标志
				ResetSpecificSignalWaitCancelFlag(DISignalId.EvaporateFlaskLevelSensor);
			}
		}

		/// <summary>
		/// 暂停打液操作
		/// </summary>
		public void PauseDispensing()
		{
			_motorControlService.PauseDispensing();
			_logger.LogInformation("已暂停打液操作");
		}

		/// <summary>
		/// 恢复打液操作
		/// </summary>
		public void ResumeDispensing()
		{
			_motorControlService.ResumeDispensing();
			_logger.LogInformation("已恢复打液操作");
		}

		/// <summary>
		/// 获取当前已打液量
		/// </summary>
		/// <returns>当前已打液量(ml)</returns>
		public double GetCurrentDispensedVolume()
		{
			return _motorControlService.GetCurrentDispensedVolume();
		}

		/// <summary>
		/// 请求取消所有信号等待操作
		/// </summary>
		/// <param name="resetAfterCancel">取消后是否立即重置取消标志</param>
		public void CancelSignalWait(bool resetAfterCancel = true)
		{
			_logger.LogInformation("已请求取消信号等待操作");
			_cancelSignalWait = true;

			if (resetAfterCancel)
			{
				Task.Delay(100).ContinueWith(_ =>
				{
					_cancelSignalWait = false;
					_logger.LogDebug("已重置信号等待取消标志");
				});
			}
		}

		/// <summary>
		/// 重置信号等待取消标志
		/// </summary>
		public void ResetSignalWaitCancelFlag()
		{
			_cancelSignalWait = false;
			_logger.LogDebug("已手动重置信号等待取消标志");
		}

		/// <summary>
		/// 等待信号状态(可取消)
		/// </summary>
		/// <param name="signalId">信号ID</param>
		/// <param name="expectedState">期望状态</param>
		/// <param name="timeoutMs">超时时间(ms)</param>
		/// <param name="holdTimeMs">持续时间(ms)</param>
		/// <param name="cancellationReason">取消原因（为空则使用默认消息）</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> WaitForSignalStateAsync(DISignalId signalId, bool expectedState, int timeoutMs, int holdTimeMs = 100, string cancellationReason = null)
		{
			try
			{
				var startTime = DateTime.Now;
				var holdStartTime = DateTime.MinValue;
				bool holdConditionMet = false;

				_logger.LogInformation($"开始等待信号 {signalId} 满足状态 {expectedState}，超时时间 {timeoutMs}ms，持续时间 {holdTimeMs}ms");

				while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
				{
					// 检查是否请求取消等待
					if (_cancelSignalWait)
					{
						string reason = !string.IsNullOrEmpty(cancellationReason)
							? cancellationReason
							: "外部请求取消等待";

						_logger.LogInformation($"信号 {signalId} 等待被取消：{reason}");
						return OperationResult.Ok($"信号等待被取消并视为成功：{reason}");
					}

					// 获取当前信号状态
					bool currentState = GetDISignalState(signalId);

					// 如果信号状态符合预期
					if (currentState == expectedState)
					{
						// 如果是第一次满足条件，记录开始时间
						if (holdStartTime == DateTime.MinValue)
						{
							holdStartTime = DateTime.Now;
							_logger.LogDebug($"信号 {signalId} 开始满足状态 {expectedState}，开始计时");
						}

						// 检查是否持续满足条件达到指定时间
						if ((DateTime.Now - holdStartTime).TotalMilliseconds >= holdTimeMs)
						{
							holdConditionMet = true;
							_logger.LogInformation($"信号 {signalId} 已持续满足状态 {expectedState} 达到 {holdTimeMs}ms");
							break;
						}
					}
					else
					{
						// 如果信号状态不符合预期，重置计时
						if (holdStartTime != DateTime.MinValue)
						{
							_logger.LogDebug($"信号 {signalId} 不再满足状态 {expectedState}，重置计时");
							holdStartTime = DateTime.MinValue;
						}
					}

					await Task.Delay(500); // 每50毫秒检查一次
				}

				if (holdConditionMet)
				{
					return OperationResult.Ok($"信号 {signalId} 已持续满足状态 {expectedState} 达到 {holdTimeMs}ms");
				}
				else
				{
					return OperationResult.Fail($"等待信号 {signalId} 满足状态 {expectedState} 超时 ({timeoutMs}ms)");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"等待信号 {signalId} 时出现异常");
				return OperationResult.Fail($"等待信号时出现异常: {ex.Message}");
			}
		}

		/// <summary>
		/// 请求取消特定信号的等待操作
		/// </summary>
		/// <param name="signalId">要取消等待的信号ID</param>
		/// <param name="cancellationReason">取消原因</param>
		/// <param name="resetAfterCancel">取消后是否立即重置取消标志</param>
		public void CancelSpecificSignalWait(DISignalId signalId, string cancellationReason = null, bool resetAfterCancel = true)
		{
			string reason = !string.IsNullOrEmpty(cancellationReason) ? cancellationReason : "外部请求取消等待";
			_logger.LogInformation($"已请求取消信号 {signalId} 的等待操作: {reason}");

			lock (_signalWaitCancelFlags)
			{
				_signalWaitCancelFlags[signalId] = true;
			}

			if (resetAfterCancel)
			{
				Task.Delay(100).ContinueWith(_ =>
				{
					lock (_signalWaitCancelFlags)
					{
						if (_signalWaitCancelFlags.ContainsKey(signalId))
						{
							_signalWaitCancelFlags[signalId] = false;
							_logger.LogDebug($"已重置信号 {signalId} 的等待取消标志");
						}
					}
				});
			}
		}

		/// <summary>
		/// 重置特定信号的等待取消标志
		/// </summary>
		/// <param name="signalId">要重置的信号ID</param>
		public void ResetSpecificSignalWaitCancelFlag(DISignalId signalId)
		{
			lock (_signalWaitCancelFlags)
			{
				if (_signalWaitCancelFlags.ContainsKey(signalId))
				{
					_signalWaitCancelFlags[signalId] = false;
				}
				else
				{
					_signalWaitCancelFlags.Add(signalId, false);
				}
			}
			_logger.LogDebug($"已手动重置信号 {signalId} 的等待取消标志");
		}

		/// <summary>
		/// 重置所有信号的等待取消标志
		/// </summary>
		public void ResetAllSignalWaitCancelFlags()
		{
			lock (_signalWaitCancelFlags)
			{
				foreach (var key in _signalWaitCancelFlags.Keys.ToList())
				{
					_signalWaitCancelFlags[key] = false;
				}
			}
			_cancelSignalWait = false; // 同时重置全局标志
			_logger.LogDebug("已手动重置所有信号的等待取消标志");
		}

		/// <summary>
		/// 等待特定信号状态(支持信号特定的取消)
		/// </summary>
		/// <param name="signalId">信号ID</param>
		/// <param name="expectedState">期望状态</param>
		/// <param name="timeoutMs">超时时间(ms)</param>
		/// <param name="holdTimeMs">持续时间(ms)</param>
		/// <param name="cancellationReason">取消原因（为空则使用默认消息）</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> WaitForSpecificSignalStateAsync(DISignalId signalId, bool expectedState, int timeoutMs, int holdTimeMs = 100, string cancellationReason = null)
		{
			try
			{
				// 确保信号在取消字典中有条目
				lock (_signalWaitCancelFlags)
				{
					if (!_signalWaitCancelFlags.ContainsKey(signalId))
					{
						_signalWaitCancelFlags.Add(signalId, false);
					}
					else
					{
						_signalWaitCancelFlags[signalId] = false; // 重置取消标志
					}
				}

				var startTime = DateTime.Now;
				var holdStartTime = DateTime.MinValue;
				bool holdConditionMet = false;

				_logger.LogInformation($"开始等待信号 {signalId} 满足状态 {expectedState}，超时时间 {timeoutMs}ms，持续时间 {holdTimeMs}ms");

				while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
				{
					// 检查是否请求取消等待(检查特定信号和全局标志)
					bool cancelRequested = false;

					lock (_signalWaitCancelFlags)
					{
						cancelRequested = _signalWaitCancelFlags.ContainsKey(signalId) && _signalWaitCancelFlags[signalId];
					}

					if (cancelRequested || _cancelSignalWait)
					{
						string reason = !string.IsNullOrEmpty(cancellationReason)
							? cancellationReason
							: "外部请求取消等待";

						_logger.LogInformation($"信号 {signalId} 等待被取消：{reason}");
						return OperationResult.Ok($"信号等待被取消并视为成功：{reason}");
					}

					// 获取当前信号状态
					bool currentState = GetDISignalState(signalId);

					// 如果信号状态符合预期
					if (currentState == expectedState)
					{
						// 如果是第一次满足条件，记录开始时间
						if (holdStartTime == DateTime.MinValue)
						{
							holdStartTime = DateTime.Now;
							_logger.LogDebug($"信号 {signalId} 开始满足状态 {expectedState}，开始计时");
						}

						// 检查是否持续满足条件达到指定时间
						if ((DateTime.Now - holdStartTime).TotalMilliseconds >= holdTimeMs)
						{
							holdConditionMet = true;
							_logger.LogInformation($"信号 {signalId} 已持续满足状态 {expectedState} 达到 {holdTimeMs}ms");
							break;
						}
					}
					else
					{
						// 如果信号状态不符合预期，重置计时
						if (holdStartTime != DateTime.MinValue)
						{
							_logger.LogDebug($"信号 {signalId} 不再满足状态 {expectedState}，重置计时");
							holdStartTime = DateTime.MinValue;
						}
					}

					await Task.Delay(500); // 每50毫秒检查一次
				}

				if (holdConditionMet)
				{
					return OperationResult.Ok($"信号 {signalId} 已持续满足状态 {expectedState} 达到 {holdTimeMs}ms");
				}
				else
				{
					return OperationResult.Fail($"等待信号 {signalId} 满足状态 {expectedState} 超时 ({timeoutMs}ms)");
				}
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"等待信号 {signalId} 时出现异常");
				return OperationResult.Fail($"等待信号时出现异常: {ex.Message}");
			}
		}

		/// <summary>
		/// 旋蒸阶段补液操作，可处理打液暂停情况
		/// </summary>
		/// <param name="pumpVolume">打液体积</param>
		/// <returns>操作结果，即使打液暂停也会返回成功</returns>
		public async Task<OperationResult> ReplenishLiquidForRotaryEvaporationAsync(double pumpVolume)
		{
			_logger.LogInformation($"开始旋蒸阶段补液操作: 打液量={pumpVolume}ml");

			try
			{
				// 1. 下插抽液针
				await ExecuteSequentialAsync(
					("移动到下插位置", "抽液平台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "下降位置离心瓶"))
				);

				// 2. 阀切换 - 打开所需阀门,破真空
				await ExecuteParallelAsync(
					("打开", "清洗三通阀1", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve1, true, 1000)),
					("打开", "清洗三通阀2", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve2, true, 1000)),
					("打开", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, true, 1000)),
					("破真空", "冷凝管", () => BreakVacuumAsync())
				);

				// 使用一个取消标记来跟踪是否应该关闭阀门
				var cts = new CancellationTokenSource();

				// 3. 启动阀门监控任务 - 如果打液暂停，则关闭阀门,建立真空
				var valveMonitorTask = Task.Run(async () =>
				{
					try
					{
						while (!cts.Token.IsCancellationRequested)
						{
							// 检查是否暂停
							if (_motorControlService.IsDispensingPaused())
							{
								_logger.LogWarning("检测到打液暂停，关闭旋蒸瓶清洗两通阀");
								await ExecuteSequentialAsync(
									("关闭", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, false, 1000)),
									("建立真空", "冷凝管", () => EstablishVacuumAsync(_condenserPressureSet, 10.0))
								);

								// 等待恢复
								while (_motorControlService.IsDispensingPaused() && !cts.Token.IsCancellationRequested)
								{
									await Task.Delay(1000, cts.Token);
								}

								// 如果恢复了并且没有被取消，重新打开阀门,破真空
								if (!cts.Token.IsCancellationRequested)
								{
									_logger.LogInformation("检测到打液恢复，重新打开旋蒸瓶清洗两通阀");
									await ExecuteSequentialAsync(
										("打开", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, true, 1000)),
										("破真空", "冷凝管", () => BreakVacuumAsync())
									);
								}
							}

							await Task.Delay(500, cts.Token);
						}
					}
					catch (OperationCanceledException)
					{
						// 正常取消，不需处理
					}
					catch (Exception ex)
					{
						_logger.LogError(ex, "阀门监控任务异常");
					}
				});

				// 4. 执行打液操作 - 设置isFirstPump=false表示这是补液
				bool isFirstPump = false;
				bool isCheckLiquidLevel = true; // 补液时要监控液位
				var pumpTask = PumpMaterialLiquidAsync(pumpVolume, isFirstPump, isCheckLiquidLevel);

				// 等待打液完成
				var pumpResult = await pumpTask;

				// 5. 停止阀门监控任务
				cts.Cancel();
				try
				{
					await valveMonitorTask;
				}
				catch (Exception ex)
				{
					_logger.LogWarning($"停止阀门监控任务时出现异常: {ex.Message}");
				}

				// 6. 关闭阀门,建立真空
				await ExecuteSequentialAsync(
					("关闭", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, false, 1000)),
					("建立真空", "冷凝管", () => EstablishVacuumAsync(_condenserPressureSet, 10.0))
				);

				// 7. 记录打液结果
				if (pumpResult.Success)
				{
					_logger.LogInformation($"旋蒸阶段补液操作完成: {pumpResult.Message}");
				}
				else
				{
					_logger.LogWarning($"旋蒸阶段补液未完全完成: {pumpResult.Message}");
				}

				// 即使打液暂停或未完成，我们也认为补液流程执行成功了
				// 因为我们已经处理了阀门的正确关闭，可以安全地返回到液位监控逻辑
				return OperationResult.Ok("旋蒸阶段补液流程执行完成");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "执行旋蒸阶段补液操作时发生异常");

				// 确保阀门关闭
				try
				{
					await SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, false, 1000);
				}
				catch (Exception valveEx)
				{
					_logger.LogError(valveEx, "关闭阀门时发生异常");
				}

				return OperationResult.Fail($"执行旋蒸阶段补液操作时发生异常: {ex.Message}");
			}
		}

		/// <summary>
		/// 建立真空并启动自动调压
		/// </summary>
		/// <param name="targetPressure">目标压力(kPa)</param>
		/// <param name="pressureTolerance">压力容差(kPa)</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> EstablishVacuumAsync(double targetPressure, double pressureTolerance = 1.0)
		{
			_logger.LogInformation($"开始建立真空，目标压力: {targetPressure}kPa，容差: ±{pressureTolerance}kPa");

			try
			{
				//1. 关闭冷凝管加料两通阀1，打开真空泵继电器
				await ExecuteSequentialAsync(
					("关闭", "冷凝管加料两通阀1", () => SwitchValveAsync(DOSignalId.CondenserAddLiquidValve1, false, 1000)),
					("打开", "真空泵继电器", () => SwitchValveAsync(DOSignalId.VacuumPumpControl, true, 1000))
				);

				// 2. 取消已有的调压任务（如果存在）并创建新的取消标记
				if (_pressureControlCts != null)
				{
					try
					{
						_pressureControlCts.Cancel();
						_pressureControlCts.Dispose();
					}
					catch (Exception ex)
					{
						_logger.LogWarning($"取消现有调压任务时出现异常: {ex.Message}");
					}
				}

				_pressureControlCts = new CancellationTokenSource();
				var token = _pressureControlCts.Token;

				// 3. 启动自动调压任务
				Task.Run(async () =>
				{
					try
					{
						_logger.LogInformation("自动调压任务已启动");

						// 最后一次操作阀门的时间
						DateTime lastValveOperationTime = DateTime.MinValue;
						// 阀门操作的最小间隔(ms)，防止频繁开关
						const int minValveOperationInterval = 2000;

						while (!token.IsCancellationRequested)
						{
							// 获取当前压力
							double currentPressure = _condenserPressure;

							// 计算与目标压力的差值
							double pressureDifference = currentPressure - targetPressure;
							bool isWithinRange = Math.Abs(pressureDifference) <= pressureTolerance;

							// 检查是否需要调节阀门
							if ((DateTime.Now - lastValveOperationTime).TotalMilliseconds >= minValveOperationInterval)
							{
								if (pressureDifference > pressureTolerance)
								{
									// 压力高于目标，打开冷凝管加料两通阀2排气
									_logger.LogDebug($"当前压力({currentPressure}kPa)高于目标范围，打开排气阀");
									await ExecuteSequentialAsync(
										("打开", "冷凝管加料两通阀2", () => SwitchValveAsync(DOSignalId.CondenserAddLiquidValve2, true, 500))
									);
									lastValveOperationTime = DateTime.Now;
								}
								else if (pressureDifference < -pressureTolerance)
								{
									// 压力低于目标，关闭冷凝管加料两通阀2
									_logger.LogDebug($"当前压力({currentPressure}kPa)低于目标范围，关闭排气阀");
									await ExecuteSequentialAsync(
										("关闭", "冷凝管加料两通阀2", () => SwitchValveAsync(DOSignalId.CondenserAddLiquidValve2, false, 500))
									);
									lastValveOperationTime = DateTime.Now;
								}
								else if (isWithinRange)
								{
									// 压力在目标范围内，记录状态
									_logger.LogDebug($"当前压力({currentPressure}kPa)在目标范围内");
								}
							}

							// 等待一段时间再检查
							await Task.Delay(500, token);
						}

						_logger.LogInformation("自动调压任务已终止");
					}
					catch (OperationCanceledException)
					{
						_logger.LogInformation("自动调压任务被取消");
					}
					catch (Exception ex)
					{
						_logger.LogError(ex, "自动调压任务发生异常");
					}
				}, token);

				return OperationResult.Ok("真空系统已启动，自动调压任务正在运行");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "建立真空时发生异常");

				// 确保关闭真空泵
				try
				{
					await SwitchValveAsync(DOSignalId.VacuumPumpControl, false, 1000);
				}
				catch (Exception valveEx)
				{
					_logger.LogError(valveEx, "关闭真空泵时发生异常");
				}

				return OperationResult.Fail($"建立真空时发生异常: {ex.Message}");
			}
		}

		/// <summary>
		/// 破真空并停止自动调压
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> BreakVacuumAsync()
		{
			_logger.LogInformation("开始破真空操作");

			try
			{
				// 1. 取消自动调压任务
				if (_pressureControlCts != null)
				{
					try
					{
						_logger.LogInformation("正在停止自动调压任务");
						_pressureControlCts.Cancel();
						// 等待一小段时间确保任务有机会响应取消请求
						await Task.Delay(500);
					}
					catch (Exception ex)
					{
						_logger.LogWarning($"取消调压任务时出现异常: {ex.Message}");
					}
					finally
					{
						_pressureControlCts.Dispose();
						_pressureControlCts = null;
					}
				}

				// 2. 先关闭真空泵继电器
				await ExecuteSequentialAsync(
					("关闭", "真空泵继电器", () => SwitchValveAsync(DOSignalId.VacuumPumpControl, false, 1000)),
					("打开", "冷凝管加料两通阀1", () => SwitchValveAsync(DOSignalId.CondenserAddLiquidValve1, true, 500)),
					("关闭", "冷凝管加料两通阀2", () => SwitchValveAsync(DOSignalId.CondenserAddLiquidValve2, false, 500))
				);
				_logger.LogInformation("已关闭真空泵继电器");

				// 3. 等待压力恢复到接近大气压
				//_logger.LogInformation("等待系统压力恢复");
				//int timeoutMs = 60000; // 60秒超时
				//var startTime = DateTime.Now;

				//while ((DateTime.Now - startTime).TotalMilliseconds < timeoutMs)
				//{
				//	if (_condenserPressure > 90) // 假设大气压约为100kPa
				//	{
				//		_logger.LogInformation($"系统压力已恢复至{_condenserPressure}kPa，破真空完成");
				//		break;
				//	}

				//	await Task.Delay(500);
				//}

				//if (_condenserPressure <= 90)
				//{
				//	_logger.LogWarning($"系统压力未完全恢复(当前{_condenserPressure}kPa)，但破真空操作已完成");
				//}

				return OperationResult.Ok("破真空操作完成");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "破真空时发生异常");
				return OperationResult.Fail($"破真空时发生异常: {ex.Message}");
			}
		}


		/// <summary>
		/// 从特定阶段恢复实验
		/// </summary>
		/// <param name="experiment">实验对象</param>
		/// <param name="resumeStage">要恢复的阶段</param>
		/// <param name="resumeSubStage">要恢复的子阶段，为null时从阶段起始点开始</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> ResumeExperimentAsync(
			Experiment experiment,
			ExperimentStage resumeStage,
			ExperimentSubStage? resumeSubStage = null)
		{
			_logger.LogInformation($"尝试从阶段 {resumeStage} {(resumeSubStage.HasValue ? $"子阶段 {resumeSubStage}" : "")} 恢复实验 {experiment.ExperimentId}");

			try
			{
				// 设置当前实验状态
				_currentExperimentId = experiment.ExperimentId;

				// 更新产物参数
				UpdateProductCurrentParameters(experiment);

				// 根据恢复阶段执行不同的操作
				OperationResult result;

				switch (resumeStage)
				{
					case ExperimentStage.MaterialAndConditionPreparation:
						// 从物料准备阶段恢复
						if (resumeSubStage.HasValue)
						{
							// 设置子阶段并恢复
							experiment.CurrentStage = ExperimentStage.MaterialAndConditionPreparation;
							experiment.CurrentSubStage = resumeSubStage.Value;
						}
						result = await ExecuteMaterialAndConditionPreparationAsync(experiment);
						if (!result.Success) return result;

						// 执行后续阶段
						goto case ExperimentStage.RotaryEvaporation;

					case ExperimentStage.RotaryEvaporation:
						// 从旋蒸阶段恢复
						if (resumeSubStage.HasValue)
						{
							experiment.CurrentStage = ExperimentStage.RotaryEvaporation;
							experiment.CurrentSubStage = resumeSubStage.Value;
						}
						result = await ExecuteRotaryEvaporationAsync(experiment);
						if (!result.Success) return result;

						// 执行后续阶段
						goto case ExperimentStage.EvaporationResidueProcessing;

					case ExperimentStage.EvaporationResidueProcessing:
						// 从旋蒸残液处理阶段恢复
						if (resumeSubStage.HasValue)
						{
							experiment.CurrentStage = ExperimentStage.EvaporationResidueProcessing;
							experiment.CurrentSubStage = resumeSubStage.Value;
						}
						result = await ExecuteEvaporationResidueProcessingAsync(experiment);
						if (!result.Success) return result;

						// 执行后续阶段
						goto case ExperimentStage.CondensateProcessing;

					case ExperimentStage.CondensateProcessing:
						// 从冷凝液处理阶段恢复
						if (resumeSubStage.HasValue)
						{
							experiment.CurrentStage = ExperimentStage.CondensateProcessing;
							experiment.CurrentSubStage = resumeSubStage.Value;
						}
						result = await ExecuteCondensateProcessingAsync(experiment);
						if (!result.Success) return result;

						// 执行后续阶段
						goto case ExperimentStage.Cleaning;

					case ExperimentStage.Cleaning:
						// 从清洗阶段恢复
						if (resumeSubStage.HasValue)
						{
							experiment.CurrentStage = ExperimentStage.Cleaning;
							experiment.CurrentSubStage = resumeSubStage.Value;
						}
						result = await ExecuteCleaningAsync(experiment);
						if (!result.Success) return result;
						break;

					default:
						return OperationResult.Fail($"无法识别的实验阶段: {resumeStage}");
				}

				return OperationResult.Ok($"成功从阶段 {resumeStage} 恢复并完成实验");
			}
			catch (OperationFailedException ex)
			{
				_logger.LogError(ex, $"从阶段 {resumeStage} 恢复实验 {experiment.ExperimentId} 时发生操作错误");
				return ex.Result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"从阶段 {resumeStage} 恢复实验 {experiment.ExperimentId} 时发生未处理异常");
				return OperationResult.Fail($"恢复实验过程中发生异常: {ex.Message}");
			}
			finally
			{
				// 重置当前状态
				if (_currentExperimentId == experiment.ExperimentId)
				{
					_currentExperimentId = null;
					_currentStage = null;
					_currentSubStage = null;
				}
			}
		}

		/// <summary>
		/// 取消液位监测并返回操作结果
		/// </summary>
		/// <returns>操作结果</returns>
		public OperationResult CancelLiquidMonitoring()
		{
			try
			{
				_logger.LogInformation("收到取消液位监测请求，操作将返回结果");
				_cancelLiquidMonitoring = true;

				// 同时取消信号等待，以防补液循环被卡在等待低液位信号的步骤
				CancelSpecificSignalWait(DISignalId.EvaporateFlaskLevelSensor, "旋蒸监测被外部取消", false);

				return OperationResult.Ok("液位监测取消成功");
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "取消液位监测时发生错误");
				return OperationResult.Fail($"取消液位监测时发生错误: {ex.Message}");
			}
		}

		/// <summary>
		/// 取消液位监测，带原因记录
		/// </summary>
		/// <param name="reason">取消原因</param>
		public void CancelLiquidMonitoring(string reason)
		{
			_logger.LogInformation($"收到取消液位监测请求，原因: {reason}");
			_cancelLiquidMonitoring = true;

			// 取消相关信号等待
			CancelSpecificSignalWait(DISignalId.EvaporateFlaskLevelSensor);
		}

		/// <summary>
		/// 工作台液体打液操作
		/// </summary>
		/// <param name="sourceItemType">源容器类型</param>
		/// <param name="targetItemType">目标容器类型</param>
		/// <param name="volumeML">打液量(ml)</param>
		/// <param name="monitorLiquidLevel">是否监控液位传感器</param>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> WorkstationLiquidDispensingAsync(
			ItemType sourceItemType,
			ItemType targetItemType,
			double volumeML,
			bool monitorLiquidLevel = false)
		{
			try
			{
				_logger.LogInformation($"开始工作台打液操作: 源容器类型={sourceItemType}, 目标容器类型={targetItemType}, 目标体积={volumeML}ml, 是否监控液位={monitorLiquidLevel}");

				// 获取抽液针和收集针的位置名称
				string extractNeedlePositionName = GetExtractNeedlePosition(sourceItemType);
				string collectNeedlePositionName = GetCollectNeedlePosition(targetItemType);

				// 并行执行针头位置调整
				await ExecuteParallelAsync(
					("移动抽液针到工作位置", "抽液平台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", extractNeedlePositionName)),
					("移动收集针到工作位置", "抽液平台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", collectNeedlePositionName))
				);

				// 并行执行阀门开关操作
				await ExecuteParallelAsync(
					("打开清洗三通阀1", "清洗三通阀1", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve1, true, 1000)),
					("打开清洗三通阀2", "清洗三通阀2", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve2, true, 1000))
				);

				// 设置泵电机ID和转换因子
				string pumpMotorId = "RotovapPump";  // 假设泵电机ID为LiquidPumpMotor
				double conversionFactor = 3.0;         // 假设转换因子为10.0 ml/圈 (需要根据实际情况调整)
				double speedRPM = 200.0;                 // 默认泵速为60 RPM

				// 重置打液量计数
				_motorControlService.ResetDispensedVolume();

				// 执行可暂停的打液操作
				var result = await ExecutePausableDispensingAsync(
					pumpMotorId,
					volumeML,
					conversionFactor,
					speedRPM,
					monitorLiquidLevel
				);

				// 判断打液是否成功
				if (!result.Success)
				{
					_logger.LogError($"工作台打液操作失败: {result.Message}");
				}
				else
				{
					_logger.LogInformation($"工作台打液操作完成: {result.Message}");
				}

				// 并行执行阀门关闭操作
				await ExecuteParallelAsync(
					("关闭清洗三通阀1", "清洗三通阀1", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve1, false, 1000)),
					("关闭清洗三通阀2", "清洗三通阀2", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve2, false, 1000))
				);

				// 并行执行复位针位置
				await ExecuteParallelAsync(
					("抬升抽液针", "抽液平台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "上升位置")),
					("抬升收集针", "抽液平台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "上升位置"))
				);

				return result;
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, $"工作台打液操作异常");
				return OperationResult.Fail($"工作台打液操作异常: {ex.Message}");
			}
		}

		// 获取抽液针位置
		private string GetExtractNeedlePosition(ItemType itemType)
		{
			switch (itemType)
			{
				case ItemType.CentrifugeBottle_500ml:
					return "下降位置离心瓶";
				case ItemType.Rotovap_500ml:
					return "下降位置样品瓶";
				case ItemType.Rotovap_1000ml:
					return "下降位置储备瓶";
				default:
					_logger.LogWarning($"未知的容器类型 {itemType}，使用默认抽液针位置");
					return "下降位置离心瓶";
			}
		}

		// 获取收集针位置
		private string GetCollectNeedlePosition(ItemType itemType)
		{
			switch (itemType)
			{
				case ItemType.CentrifugeBottle_500ml:
					return "下降位置离心瓶";
				case ItemType.SampleBottle_8ml:
					return "下降位置取样瓶";
				default:
					_logger.LogWarning($"未知的容器类型 {itemType}，使用默认收集针位置");
					return "下降位置离心瓶";
			}
		}

		public static bool test;
		/// <summary>
		/// 设备初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeDevicesAsync()
		{
			try
			{
				_logger.LogInformation("领域服务: 开始执行设备初始化");

				#region 打液体测试

				////3.原液输送
				//await ExecuteSequentialAsync(
				//	("原液输送", "旋蒸补液泵", () => PumpMaterialLiquidAsync(50, true, false))
				//);

				//await ExecuteSequentialAsync(
				//	("原液输送", "旋蒸补液泵", () => PumpMaterialLiquidAsync(50, true, false))
				//);



				#endregion


				#region   夹持电机测试

				//if (test)
				//{
				//	await ExecuteSequentialAsync(
				//		("移动到夹紧位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "夹紧位置")),
				//		("移动到夹紧位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "夹紧位置"))
				//	);
				//	test = false;
				//}
				//else
				//{
				//	await ExecuteParallelAsync(
				//		("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
				//		("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
				//	);
				//	test = true;
				//}


				//await ExecuteSequentialAsync(
				//	("开盖", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "旋开位置"))
				//);


				////await ExecuteSequentialAsync(
				////	("关盖", "开关盖旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("BottleRotateMotor", 800, 500, 60000, 25))
				////);


				////测试归为
				//await ExecuteSequentialAsync(
				//	("回归到安装位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", 0, 160000.0, 160000.0, 160000.0))
				//);


				//_logger.LogInformation("领域服务: 设备初始化完成");
				//return new OperationResult { Success = true, Message = "设备初始化完成" };



				#endregion


				#region 出库

				////5、等待机器人空闲发送放瓶任务    
				//var robotPlaceTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromShelf_Plate,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 105
				//};
				//robotPlaceTaskSendDto.BottleType = 3;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送放任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
				//	($"执行放任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromShelf_Plate + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

				//);

				////5、等待机器人空闲发送放瓶任务
				//var robotPlaceTaskSendDto1 = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToExternal,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 2
				//};

				//robotPlaceTaskSendDto1.BottleType = 3;


				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送放任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto1)),
				//	($"执行放任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToExternal + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

				//);



				#endregion

				#region  开盖测试

				//// 4、等待机器人空闲,并发送取瓶任务

				//var robotPickTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromShelf_Bottle,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 101
				//};
				//robotPickTaskSendDto.BottleType = 3;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送取任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
				//	($"执行取任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromShelf_Bottle + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				//);

				////5、等待机器人空闲,并发送放瓶任务
				//var robotPlaceTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToWorkStation,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 3
				//};
				//robotPlaceTaskSendDto.BottleType = 3;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送放任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
				//	($"执行放任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人到开盖位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000))
				//);

				//await ExecuteSequentialAsync(
				//	("移动到夹紧位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "夹紧位置")),
				//	("移动到夹紧位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "夹紧位置"))
				//);

				//await ExecuteSequentialAsync(
				//	("发送机器人继续执行信号——松开去夹盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人夹到盖子", "机器人", () => WaitForRobotSignalAsync(1, 2, 1200000)),
				//	("开盖", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "旋开位置")),
				//	("发送机器人继续执行信号——放盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 2, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人夹瓶身到位", "机器人", () => WaitForRobotSignalAsync(1, 3, 1200000))
				//);

				//await ExecuteParallelAsync(
				//	("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
				//	("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
				//);

				//await ExecuteSequentialAsync(
				//	("发送机器人继续执行信号——可取走至抽液平台", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 3, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToWorkStation + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0)),
				//	("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置"))
				//);






				#endregion


				#region 关盖测试


				//var robotPickTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromWorkStation,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 3
				//};
				//robotPickTaskSendDto.BottleType = 3;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送取任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
				//	($"执行取任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人到关盖位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000))
				//);

				//await ExecuteSequentialAsync(
				//	("移动到夹紧位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "夹紧位置")),
				//	("移动到夹紧位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "夹紧位置"))
				//);

				//await ExecuteSequentialAsync(
				//	("发送机器人继续执行信号——松开去取盖", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人取盖到达关盖位", "机器人", () => WaitForRobotSignalAsync(1, 2, 1200000)),
				//	("关盖", "开关盖旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("BottleRotateMotor", 800, 500, 60000, 60)),
				//	("发送机器人继续执行信号——夹瓶身", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 2, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人夹瓶身到位", "机器人", () => WaitForRobotSignalAsync(1, 3, 1200000))
				//);

				//await ExecuteParallelAsync(
				//	("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
				//	("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))
				//);

				//await ExecuteSequentialAsync(
				//	("发送机器人继续执行信号——可取走至抽液平台", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 3, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromWorkStation + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0)),
				//	("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置"))
				//);



				////5、等待机器人空闲发送放瓶任务
				//var robotPlaceTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToShelf_Bottle,
				//	BottleType = (ushort)ItemType.CentrifugeBottle_500ml,
				//	Position = 301
				//};
				//robotPlaceTaskSendDto.BottleType = 3;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	($"发送放任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
				//	($"执行放任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToShelf_Bottle + 1000, 1200000)),
				//				("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

				//);






				#endregion


				#region  安装旋蒸瓶


				//var robotPickTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromShelf_Bottle,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 402
				//};
				//robotPickTaskSendDto.BottleType += 1;


				//// 3、等待机器人空闲,并发送取瓶任务
				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	("发送取旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto)),
				//	("执行取旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromShelf_Bottle + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				//);

				//var robotPlaceTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToRotaryStation,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 5
				//};
				//robotPlaceTaskSendDto.BottleType += 1;

				//// 4、等待机器人空闲,并发送放瓶任务
				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	("发送安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto)),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人移动至旋蒸瓶安装位", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000)),
				//	("旋紧旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", -600, 800, 50000, 15)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToRotaryStation + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				//);


				//await ExecuteSequentialAsync(
				//	("旋紧旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", -600, 800, 50000, 15))
				//);


				//var currentAngle = 900; ;
				////计算回归角度,会到离当前位置最近的角度_rotaryBottleTightenAngle
				//var currentFullRotations = Math.Floor(currentAngle / 360.0);
				//var targetAngle = (currentFullRotations * 360.0) + (50 % 360.0);


				#endregion


				#region 卸载旋蒸瓶

				////4.等待机器人空闲并发送拆卸旋蒸瓶任务
				//var robotPickTaskSendDto1 = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromRotaryStation,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 5
				//};
				//robotPickTaskSendDto1.BottleType += 1;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	("发送拆卸旋蒸瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto1)),
				//	("执行拆卸旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人夹住旋蒸瓶", "机器人", () => WaitForRobotSignalAsync(1, 1, 1200000)),
				//	("松开旋蒸瓶", "旋蒸旋转电机", () => _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", 600, 800, 50000, 20)),
				//	("发送机器人继续执行信号——取走旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromRotaryStation + 1000, 1200000)),
				//	("发送机器人继续执行信号——取走旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行拆卸旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))

				//);

				////5、等待机器人空闲，发送放瓶任务
				//var robotPlaceTaskSendDto1 = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToShelf_Bottle,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 402
				//};
				//robotPlaceTaskSendDto1.BottleType += 1;

				//await ExecuteSequentialAsync(
				//	("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 1200000)),
				//	("发送放瓶任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto1)),
				//	("执行放瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
				//	("等待机器人完成任务", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.PlaceToShelf_Bottle + 1000, 1200000)),
				//	("发送机器人继续执行信号——松开旋蒸瓶", "机器人", () => _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 })),
				//	("执行安装旋蒸瓶任务", "机器人", () => _deviceManager.Robot.StartAsync(0))
				//);


				#endregion

				#region test

				////记录旋紧后角度
				//var actStatus = await _motorControlService.GetMotorStatusAsync("RotovapRotaryMotor");
				//_rotaryBottleTightenAngle = actStatus.Actual_P;


				//var actStatus1 = await _motorControlService.GetMotorStatusAsync("RotovapRotaryMotor");
				//var currentAngle = actStatus1.Actual_P;
				////计算回归角度,会到离当前位置最近的角度_rotaryBottleTightenAngle
				//var currentFullRotations = Math.Floor(currentAngle / 360.0);
				//var targetAngle = (currentFullRotations * 360.0) + (_rotaryBottleTightenAngle % 360.0);
				//await ExecuteSequentialAsync(
				//	("回归到安装位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", targetAngle, 100, 100, 100))
				//);

				//				await ExecuteSequentialAsync(
				//	("回零", "旋蒸旋转电机", () => _motorControlService.HomeMotorAsync("RotovapRotaryMotor")),
				//	("回归到卸载位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", "卸载位"))
				//);

				#endregion



				#region   初始化

				//var actStatus = await _motorControlService.GetMotorStatusAsync("RotovapRotaryMotor");
				//var currentAngle = actStatus.Actual_P;
				////计算回归角度,会到离当前位置最近的角度_rotaryBottleTightenAngle
				//var currentFullRotations = Math.Floor(currentAngle / 360.0);
				//var targetAngle = (currentFullRotations * 360.0) + (_rotaryBottleTightenAngle % 360.0);

				//				await ExecuteSequentialAsync(
				//	("回归到安装位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", 10, 100, 100, 100))
				//);

				//				await ExecuteSequentialAsync(
				//	("原液输送", "旋蒸补液泵", () => PumpMaterialLiquidAsync(450, true, false))///test
				//);


				// 通过设备领域服务更新设备状态为初始化中
				await _deviceService.SetDeviceModeAsync(DeviceEnums.DeviceMode.Maintenance);

				// 更新设备状态为初始化中
				var deviceStatus = DeviceEnums.DeviceStatus.Initializing;
				_deviceService.UpdateDeviceStatus(deviceStatus);

				//// 先初始化机械手
				//var robotResult = await InitializeRobotAsync();
				//if (!robotResult.Success)
				//{
				//	_logger.LogWarning($"领域服务: 机械手初始化失败: {robotResult.Message}");
				//	_deviceService.UpdateDeviceStatus(DeviceEnums.DeviceStatus.Error);
				//	return robotResult;
				//}




				// 创建其他初始化任务
				var liquidHandlingTask = InitializeLiquidHandlingWorkstationAsync();
				var rotaryEvaporatorTask = InitializeRotaryEvaporatorWorkstationAsync();
				var fluidSystemTask = InitializeFluidSystemAsync();

				// 创建超时任务
				var timeoutTask = Task.Delay(TimeSpan.FromMinutes(5)); // 设置5分钟超时

				// 等待所有任务完成或超时
				var completedTask = await Task.WhenAny(
					Task.WhenAll(liquidHandlingTask, rotaryEvaporatorTask, fluidSystemTask),
					timeoutTask
				);

				// 检查是否超时
				if (completedTask == timeoutTask)
				{
					_logger.LogError("领域服务: 设备初始化超时");
					_deviceService.UpdateDeviceStatus(DeviceEnums.DeviceStatus.Error);
					return new OperationResult { Success = false, Message = "设备初始化超时" };
				}

				// 检查每个初始化结果
				var results = new[]
				{
					await liquidHandlingTask,
					await rotaryEvaporatorTask,
					await fluidSystemTask
				};

				var failedResults = results.Where(r => !r.Success).ToList();
				if (failedResults.Any())
				{
					var errorMessage = string.Join("; ", failedResults.Select(r => r.Message));
					_logger.LogError($"领域服务: 设备初始化部分失败: {errorMessage}");
					_deviceService.UpdateDeviceStatus(DeviceEnums.DeviceStatus.Error);
					return new OperationResult { Success = false, Message = $"设备初始化部分失败: {errorMessage}" };
				}

				// 所有初始化成功，更新设备状态为空闲
				_deviceService.UpdateDeviceStatus(DeviceEnums.DeviceStatus.Idle);

				#endregion


				#region

				//// 4. 等待机器人空闲并发送拆卸旋蒸瓶任务
				//var robotPickTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PickFromRotaryStation,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 5
				//};
				//robotPickTaskSendDto.BottleType += 1;

				//await WaitForRobotSignalAsync(0,0, 1200000);

				//await _deviceManager.Robot.SetTaskParametersAsync(robotPickTaskSendDto);

				//await _deviceManager.Robot.StartAsync(1);
				////await WaitForRobotSignalAsync(1, 1, 1200000);
				////await _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", 600, 800, 50000, 30);
				////await _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 });
				////await WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromRotaryStation + 1000, 1200000);
				////await _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 });
				////await _deviceManager.Robot.StartAsync(0);
				////await _motorControlService.HomeMotorAsync("RotovapRotaryMotor");



				//// 获取并输出初始内存使用情况
				//long initialMemory = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"初始内存使用: {initialMemory} MB");

				//_logger.LogInformation("准备执行: WaitForRobotSignalAsync(1, 1, 1200000)");
				//await WaitForRobotSignalAsync(1, 1, 1200000);
				//long memory1 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤1完成后内存使用: {memory1} MB, 增加: {memory1 - initialMemory} MB");

				//_logger.LogInformation("准备执行: ExecuteTorqueControlAsync");
				//await _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", 600, 800, 50000, 30);
				//long memory2 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤2完成后内存使用: {memory2} MB, 增加: {memory2 - memory1} MB");

				//_logger.LogInformation("准备执行: HandleProcessSignalsAsync(WaitingPoint1Confirm = 1)");
				//await _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 });
				//long memory3 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤3完成后内存使用: {memory3} MB, 增加: {memory3 - memory2} MB");

				//_logger.LogInformation("准备执行: WaitForRobotSignalAsync(2)");
				//await WaitForRobotSignalAsync(2, (ushort)TaskType.PickFromRotaryStation + 1000, 1200000);
				//long memory4 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤4完成后内存使用: {memory4} MB, 增加: {memory4 - memory3} MB");

				//_logger.LogInformation("准备执行: HandleProcessSignalsAsync(所有Confirm = 0)");
				//await _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 0, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 });
				//long memory5 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤5完成后内存使用: {memory5} MB, 增加: {memory5 - memory4} MB");

				//_logger.LogInformation("准备执行: Robot.StartAsync(0)");
				//await _deviceManager.Robot.StartAsync(0);
				//long memory6 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤6完成后内存使用: {memory6} MB, 增加: {memory6 - memory5} MB");

				//_logger.LogInformation("准备执行: HomeMotorAsync");
				//await _motorControlService.HomeMotorAsync("RotovapRotaryMotor");
				//long memory7 = Process.GetCurrentProcess().WorkingSet64 / 1024 / 1024;
				//_logger.LogInformation($"步骤7完成后内存使用: {memory7} MB, 总增加: {memory7 - initialMemory} MB");



				////5、等待机器人空闲，发送放瓶任务
				//var robotPlaceTaskSendDto = new RobotTaskSendDto
				//{
				//	TaskType = TaskType.PlaceToShelf_Bottle,
				//	BottleType = (ushort)ItemType.Rotovap_1000ml,
				//	Position = 305
				//};
				//robotPlaceTaskSendDto.BottleType += 1;

				//await WaitForRobotSignalAsync(0, 0, 1200000);
				//await _deviceManager.Robot.SetTaskParametersAsync(robotPlaceTaskSendDto);
				//await _deviceManager.Robot.StartAsync(1);
				//await WaitForRobotSignalAsync(1, 1, 1200000);
				//await _motorControlService.ExecuteTorqueControlAsync("RotovapRotaryMotor", 600, 800, 50000, 30);
				//await _deviceManager.Robot.HandleProcessSignalsAsync(new RobotProcessSignalsDto { WaitingPoint1Confirm = 1, WaitingPoint2Confirm = 0, WaitingPoint3Confirm = 0 });



				#endregion

				// 恢复手动模式
				await _deviceService.SetDeviceModeAsync(DeviceEnums.DeviceMode.Manual);

				_logger.LogInformation("领域服务: 设备初始化完成");
				return new OperationResult { Success = true, Message = "设备初始化完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域服务: 设备初始化过程中发生错误");

				// 更新设备状态为错误
				_deviceService.UpdateDeviceStatus(DeviceEnums.DeviceStatus.Error);

				return new OperationResult
				{
					Success = false,
					Message = $"设备初始化失败: {ex.Message}"
				};
			}
		}

		/// <summary>
		/// 液体处理工作台初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeLiquidHandlingWorkstationAsync()
		{
			try
			{
				_logger.LogInformation("领域服务: 开始初始化液体处理工作台");

				await ExecuteParallelAsync(
					("移动到上升位置", "工作台抽液针升降电机", () => _motorControlService.MoveToPositionAsync("ExtractLiquidLiftMotor", "上升位置")),
					("移动到上升位置", "工作台收集针升降电机", () => _motorControlService.MoveToPositionAsync("CollectLiquidLiftMotor", "上升位置")),
					//("移动到上升位置", "工作台取样针升降电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidLiftMotor", "上升位置")),
					///("移动到初始位置", "洗液槽电机", _motorControlService.MoveToPositionAsync("WashingTankMotor", "初始位置")),
					//("移动到关闭位置", "外部升降门电机", _motorControlService.MoveToPositionAsync("ExternalLiftDoorMotor", "关闭位置")),
					("回到初始位置", "开关盖旋转电机", () => _motorControlService.MoveToPositionAsync("BottleRotateMotor", "初始位置")),
					("移动到松开位置", "开关盖夹持电机1", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor1", "松开位置")),
					("移动到松开位置", "开关盖夹持电机2", () => _motorControlService.MoveToPositionAsync("BottleHolderMotor2", "松开位置"))//,
																														 //("旋转到初始位置", "工作台取样针旋转电机", () => _motorControlService.MoveToPositionAsync("SampleLiquidRotateMotor", "初始位置"))
				);

				_logger.LogInformation("领域服务: 液体处理工作台初始化完成");
				return new OperationResult { Success = true, Message = "液体处理工作台初始化完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域服务: 液体处理工作台初始化过程中发生错误");
				return new OperationResult { Success = false, Message = $"液体处理工作台初始化失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 旋蒸工作台初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeRotaryEvaporatorWorkstationAsync()
		{
			try
			{
				_logger.LogInformation("领域服务: 开始初始化旋蒸工作台");

				await ExecuteParallelAsync(
					("移动到上升位置", "旋蒸升降电机", () => _motorControlService.MoveToPositionAsync("RotovapLiftMotor", "上升位置")),
					("移动到安装位", "旋蒸旋转电机", () => _motorControlService.MoveToPositionAsync("RotovapRotaryMotor", "安装位"))
				);

				var oilBath = _deviceManager.GetOilBath("OilBath_503_1");
				var tcu = _deviceManager.GetTCU("TCU_502_1");

				await ExecuteSequentialAsync(
					//("打开油浴锅盖", "油浴锅", OperateOilBathCoverAsync(true)),
					("移动到收回位置", "油浴锅电机", () => _motorControlService.MoveToPositionAsync("OilBathMotor", "收回位置")),
					("关闭加热", "油浴锅", () => oilBath.SetRunningStatusAsync(2))
				//("关闭制冷", "冷凝器", tcu.AllowCoolingSwitchAsync(false))
				);


				_logger.LogInformation("领域服务: 旋蒸工作台初始化完成");
				return new OperationResult { Success = true, Message = "旋蒸工作台初始化完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域服务: 旋蒸工作台初始化过程中发生错误");
				return new OperationResult { Success = false, Message = $"旋蒸工作台初始化失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 液路系统初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeFluidSystemAsync()
		{
			try
			{
				_logger.LogInformation("领域服务: 开始初始化液路系统");

				var switchValve = _deviceManager.GetValve("Valve_COM8_0");

				await ExecuteParallelAsync(
					("破真空", "冷凝管", () => BreakVacuumAsync()),
					("关闭", "清洗三通阀1", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve1, false, 1000)),
					("关闭", "清洗三通阀2", () => SwitchValveAsync(DOSignalId.WashingThreeWayValve2, false, 1000)),
					("关闭", "洗液桶三通阀", () => SwitchValveAsync(DOSignalId.WashingLiquidBucketThreeWayValve, false, 1000)),
					("关闭", "进液台两通阀1", () => SwitchValveAsync(DOSignalId.FeedingLiquidValve1, false, 1000)),
					("关闭", "进液台两通阀2", () => SwitchValveAsync(DOSignalId.FeedingLiquidValve2, false, 1000)),
					("关闭", "取液模块两通阀", () => SwitchValveAsync(DOSignalId.ExtractionLiquidValve, false, 1000)),
					//("复位", "六通切换阀", () => switchValve.ResetAsync()),
					("关闭", "冷凝管洗液两通阀", () => SwitchValveAsync(DOSignalId.CondenserWashLiquidValve, false, 1000)),
					("关闭", "旋蒸瓶清洗两通阀", () => SwitchValveAsync(DOSignalId.EvaporateFlaskCleanValve, false, 1000)),
					("关闭", "冷凝液回收两通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleValve, false, 1000)),
					("关闭", "冷凝液回收三通阀", () => SwitchValveAsync(DOSignalId.CondensateRecycleThreeWayValve, false, 1000)),
					("关闭", "排冷凝液两通阀", () => SwitchValveAsync(DOSignalId.ExhaustCondensateLiquidValve, false, 1000))
				//冷凝液通断电机
				);

				_logger.LogInformation("领域服务: 液路系统初始化完成");
				return new OperationResult { Success = true, Message = "液路系统初始化完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域服务: 液路系统初始化过程中发生错误");
				return new OperationResult { Success = false, Message = $"液路系统初始化失败: {ex.Message}" };
			}
		}

		/// <summary>
		/// 机械手初始化
		/// </summary>
		/// <returns>操作结果</returns>
		public async Task<OperationResult> InitializeRobotAsync()
		{
			try
			{
				_logger.LogInformation("领域服务: 开始初始化机械手");

				//定义机械手初始化任务
				var robotTask = new RobotTaskSendDto
				{
					TaskType = TaskType.MoveToHome, // 移动到机械手原点
					BottleType = 501,
					Position = 0,
					NeedScan = 0,
					Reserved1 = 0,
					Reserved2 = 0
				};

				await ExecuteSequentialAsync(
					("等待机器人空闲", "机器人", () => WaitForRobotSignalAsync(0, 0, 120000)),
					("发送机械手初始化任务", "机器人", () => _deviceManager.Robot.SetTaskParametersAsync(robotTask)),
					("执行机械手初始化任务", "机器人", () => _deviceManager.Robot.StartAsync(1)),
					("等待机械手初始化完成", "机器人", () => WaitForRobotSignalAsync(2, (ushort)TaskType.MoveToHome + 1000, 120000))
				);

				_logger.LogInformation("领域服务: 机械手初始化完成");
				return new OperationResult { Success = true, Message = "机械手初始化完成" };
			}
			catch (Exception ex)
			{
				_logger.LogError(ex, "领域服务: 机械手初始化过程中发生错误");
				return new OperationResult { Success = false, Message = $"机械手初始化失败: {ex.Message}" };
			}
		}

	}
}
